How to match a String against string literals?
You could also do
match &stringthing as &str {
"a" => println!("0"),
"b" => println!("1"),
"c" => println!("2"),
_ => println!("something else!"),
}
See:
std::string::String
std::ops::Deref
- Deref coercions
UPDATE:
Use .as_str()
like this to convert the String
to an &str
:
match stringthing.as_str() {
"a" => println!("0"),
"b" => println!("1"),
"c" => println!("2"),
_ => println!("something else!"),
}
Reason
.as_str()
is more concise and enforces stricter type checking. The trait as_ref
is implemented for multiple types and its behaviour could be changed for type String
, leading to unexpected results. Similarly, if the input argument changes type, the compiler will not signal a problem when that type implements the trait 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
Old answer:
as_slice
is deprecated, you should now use the trait std::convert::AsRef
instead:
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:
match stringthing.as_str() {
"a" => println!("0"),
"b" => println!("1"),
"c" => println!("2"),
_ => println!("something else!"),
}