我试图找出如何匹配StringRust 中的一个。我最初尝试像这样进行匹配,但是我发现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如何String在Rust中实际匹配s?
3 回答
明月笑刀无情
TA贡献1828条经验 获得超4个赞
你也可以
match &stringthing as &str {
"a" => println!("0"),
"b" => println!("1"),
"c" => println!("2"),
_ => println!("something else!"),
}
添加回答
举报
0/150
提交
取消