How to match a String against string literals?

ID : 10300

viewed : 45

Tags : stringmatchruststring

Top 5 Answer for How to match a String against string literals?

vote vote

98

UPDATE Use .as_str()

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.

vote vote

80

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!"), } 
vote vote

73

You could also do

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

See:

vote vote

63

Editor's note: This answer pertains to an version of Rust before 1.0 and does not work in 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!"), } 
vote vote

58

You can try:

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

Top 3 video Explaining How to match a String against string literals?

Related QUESTION?