【翻译】在Rust中字符串如何匹配?

How to match a String against string literals in Rust?

在Rust中字符串如何匹配?


I'm trying to figure out how to match a String in Rust.

我试图弄清楚Rust中是如何匹配一个字符串类型的。


I initially tried matching like this, but I figured out Rust cannot implicitly cast from std::string::String to &str.

我最初这样尝试,但是我发现Rust不能隐式的从std::string::String转化为&str。


fn main() {

    let stringthing = String::from("c");

    match stringthing {

        "a" => println!("0"),

        "b" => println!("1"),

        "c" => println!("2"),

    }

}

This has the error:

这里的错误:

error[E0308]: mismatched types

--> src/main.rs:4:9

  |

4 |        "a" => println!("0"),

  |        ^^^ expected struct `std::string::String`, found reference

  |

  = note: expected type `std::string::String`

            found type `&'static str`

I then tried to construct new String objects, as I could not find a function to cast a String to a &str.

接着我尝试创建一个新的String对象,因为我不能找到一个方法将String转化为一个&str。

fn main() {

    let stringthing = String::from("c");

    match stringthing {

        String::from("a") => println!("0"),

        String::from("b") => println!("1"),

        String::from("c") => println!("2"),

    }

}

This gave me the following error 3 times:

编译器给我提示了如下的错误3次:


error[E0164]: `String::from` does not name a tuple variant or a tuple struct

--> src/main.rs:4:9

  |

4 |        String::from("a") => return 0,

  |        ^^^^^^^^^^^^^^^^^ not a tuple variant or struct

How to actually match Strings in Rust?

那在Rust中到底是如何匹配String的呢?


You can do something like this:

你可以这样处理:


match &stringthing[..] {

    "a" => println!("0"),

    "b" => println!("1"),

    "c" => println!("2"),

    _ => println!("something else!"),

}

There's also an as_str method as of Rust 1.7.0:

在Rust1.7.0之后,你也可以使用as_str方法:


match stringthing.as_str() {

    "a" => println!("0"),

    "b" => println!("1"),

    "c" => println!("2"),

    _ => println!("something else!"),

}


stringthing.as_str() is probably the most straightforward of all the answers; I don't like as_ref because it's unnecessarily general, which can lead to bugs, and not as explicit, it isn't completely clear that as_ref() is going to be a &str, as_str is simple and clear.

在所有答案中,stringthing.as_str()方法可能是最直接的。我不喜欢as_ref方法,因为它通常是不必要的,这样做会导致bug并且是不显示的,as_ref()是否会是一个&str类型不是那么清楚,而as_str方法简单明了。


@Zorf You are right. The answer was accepted when as_str did not exist yet. I changed the accepted answer but thank all people who answered this question!

@Zorf 你是正确的。之前as_str不存在时我接受的这个答案。我已经更改了接受的答案,但还是要感谢所有回答这个问题的同学。

你可能感兴趣的:(【翻译】在Rust中字符串如何匹配?)