简体   繁体   English

如何将字符串与字符串文字匹配?

[英]How to match a String against string literals?

I'm trying to figure out how to match a String in Rust.我想弄清楚如何在 Rust 中匹配String

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 String s in Rust?如何在 Rust 中实际匹配String

UPDATE Use .as_str()更新使用.as_str()

Reason .as_str() is more concise and enforces stricter type checking. Reason .as_str()更简洁并强制执行更严格的类型检查。 The trait as_ref is implemented for multiple types and its behaviour could be changed for type String , leading to unexpected results.特性as_ref是为多种类型实现的,它的行为可以改变为String类型,从而导致意外结果。 Similarly, if the input argument changes type, the compiler will not signal a problem when that type implements the trait as_ref .类似地,如果输入参数改变类型,当该类型实现特性as_ref时,编译器不会发出问题信号。

The docs suggest to use as_str as well https://doc.rust-lang.org/std/string/struct.String.html , https://doc.rust-lang.org/std/primitive.str.html文档建议也使用as_str https://doc.rust-lang.org/std/string/struct.String.htmlhttps://doc.rust-lang.org/std/primitive.str.html

Old answer:旧答案:

as_slice is deprecated, you should now use the trait std::convert::AsRef instead: as_slice已弃用,您现在应该使用特征std::convert::AsRef代替:

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

Note that you also have to explicitly handle the catch-all case.请注意,您还必须明确处理包罗万象的情况。

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:从 Rust 1.7.0 开始,还有一个as_str方法:

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

You could also do你也可以这样做

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

See:看:

Editor's note: This answer pertains to an version of Rust before 1.0 and does not work in Rust 1.0编者注:此答案适用于 1.0 之前的 Rust 版本,不适用于 Rust 1.0

You can match on a string slice.您可以匹配字符串切片。

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

You can try:你可以试试:

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

You can convert the String into &str by doing this:您可以通过执行以下操作将String转换为&str

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

Use as_str() on Strings to get string slice在字符串上使用 as_str() 来获取字符串切片

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

if your taking input from the console and want to perform match on it be sure to call trim() after as_str() to remove escape character ie '\n' from the input.如果您从控制台获取输入并想对其执行匹配,请务必在 as_str() 之后调用 trim() 以从输入中删除转义字符,即 '\n'。 As in如在

match stringthing.as_str().trim() {...}


You can convert the String to a &str using the as_str() method, and then match on the &str value like so:您可以使用 as_str() 方法将 String 转换为 &str,然后像这样匹配 &str 值:

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

Or you can bind the String value to a variable, and then match on the variable like so:或者您可以将 String 值绑定到一个变量,然后像这样在变量上进行匹配:

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

Or you can use the == operator to compare the String value with a string literal like so:或者您可以使用 == 运算符将字符串值与字符串文字进行比较,如下所示:

fn main() {
    let stringthing = String::from("c");
    if stringthing == "a" {
        println!("0");
    } else if stringthing == "b" {
        println!("1");
    } else if stringthing == "c" {
        println!("2");
    } else {
        println!("other");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM