我试图弄清楚如何匹配Rust中的字符串。
我最初尝试这样匹配,但我发现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中匹配字符串?