如何在Rust中匹配字符串与字符串文字?

时间:2014-08-19 12:30:02

标签: string match rust

我正在试图弄清楚如何匹配Rust中的String

我最初尝试过像这样匹配,但我发现Rust无法隐式地从std::string::String投射到&str

fn main() {
    let stringthing = String::from("c");
    match stringthing {
        "a" => println!("0"),
        "b" => println!("1"),
        "c" => println!("2"),
    }
}

这有错误:

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`

然后我尝试构建新的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"),
    }
}

这给了我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

如何在Rust中实际匹配String

6 个答案:

答案 0 :(得分:135)

as_slice已弃用,您现在应该使用特征std::convert::AsRef代替:

match stringthing.as_ref() {
    "a" => println!("0"),
    "b" => println!("1"),
    "c" => println!("2"),
    _ => println!("something else!"),
}

请注意,您还必须明确处理catch-all案例。

答案 1 :(得分:19)

您可以这样做:

match &stringthing[..] {
    "a" => println!("0"),
    "b" => println!("1"),
    "c" => println!("2"),
    _ => println!("something else!"),
}

从Rust 1.7.0开始,还有一个as_str方法:

match stringthing.as_str() {
    "a" => println!("0"),
    "b" => println!("1"),
    "c" => println!("2"),
    _ => println!("something else!"),
}

答案 2 :(得分:12)

您也可以

match &stringthing as &str {
    "a" => println!("0"),
    "b" => println!("1"),
    "c" => println!("2"),
    _ => println!("something else!"),
}

请参阅:

答案 3 :(得分:10)

  

编者注:这个答案适用于1.0之前的Rust版本,并且在Rust 1.0中不起作用

您可以匹配字符串切片。

match stringthing.as_slice() {
    "a" => println!("0"),
    "b" => println!("1"),
    "c" => println!("2"),
    _ => println!("something else!"),
}

答案 4 :(得分:1)

您可以尝试:

fn main() {
    let stringthing = String::from("c");
    match &*stringthing {
        "a" => println!("0"),
        "b" => println!("1"),
        "c" => println!("2"),
        _ => println!("else")
    }
}

答案 5 :(得分:1)

您可以通过执行以下操作将 String 转换为 &str

fn main() {
    let stringthing = String::from("c");
    match &stringthing[..] {
        "a" => println!("0"),
        "b" => println!("1"),
        "c" => println!("2"),
    }
}