如何在 Rust 中匹配字符串 [英] How to match Strings in Rust

查看:95
本文介绍了如何在 Rust 中匹配字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 Rust lang 中匹配 String ,但我不能:

I tried to match Strings in Rust lang but I can't:

for (key, value) in obj.iter() {
    let valueType = match Some(value.to_string()) {
        Some(ref x) if x == "some_value" => string_gen(),
        _ => "test".to_string()
    };
    println!("{}", value);
    println!("{}", valueType);
}

当迭代器的值为some_value"时,我必须匹配单词some_value"

I have to match the word "some_value" when the value of the iterator is "some_value"

我进行了大量搜索,发现有很多人遇到了同样的问题.

I did a lot of searches and have a lot of people with the same problems.

推荐答案

你可以通过从 String 中取出一个 &str 来实现,比如这样:

You can do it by getting a &str out of the String, such as with this:

match Some(&*value.to_string()) {
    Some("some_value") => string_gen(),
    _ => "test".to_string()
}

但就直接匹配 String 的模式而言:不,你不能.模式匹配完全是关于结构比较,而不是像 == 这样的任意用户定义的代码比较.String 是一个结构体类型,有一些私有字段,所以你无法匹配它的内部.你只能从中得到一个可以比较的 &str.

But as far as pattern matching a String directly: no, you can’t. Pattern matching is all about structural comparisons rather than arbitrary user-defined code comparisons like == is able to do. String is a struct type with a handful of private fields, so you can’t match its insides. You can only get a &str out of it which can be compared.

这篇关于如何在 Rust 中匹配字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆