【发布时间】:2014-10-12 13:23:17
【问题描述】:
我试图弄清楚如何在 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 中实际匹配 Strings?
【问题讨论】:
-
stringthing.as_str()可能是所有答案中最直接的;我不喜欢as_ref,因为它过于笼统,可能导致错误,而且不那么明确,as_ref()是否会成为&str并不完全清楚,as_str简单明了. -
@Zorf 你是对的。当
as_str尚不存在时,答案被接受。我更改了接受的答案,但感谢所有回答此问题的人!