How to match Strings in Rust

2019-06-14 12:03发布

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);
}

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 rust
1条回答
Anthone
2楼-- · 2019-06-14 12:27

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()
}

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.

查看更多
登录 后发表回答