How to match a String against string literals in Rust example
This explains compare the comparison string with the string literal in with example in Rust.
String and string literals are two different objects.
String literals are string slices that can be declared.
let name = "one";
String object type can be created as follows.
let name1 = String::from("one");
Rust String matching with String literals
Rust provides a matching case, similar to a switch in java, used to match an expression with a set of values and executes the matching case.
Match express and case expression should match, otherwise throws a mismatched type error.
String objects need to convert to string literal as &str
in multiple ways.
There are multiple ways we can compare String objects with string literals or slices.
One way using match with as_str
,
Used match case, with String object which converts to String literal as &str
using as_str()
method, This slice can be checked again multiple cases and executed matched case.
Here is an example.
fn main() {
let name = String::from("one");
match name.as_str() {
"one" => println!("1"),
"two" => println!("2"),
"three" => println!("3"),
_ => println!("Default"),
}
}
Output:
1
The second way uses accessing the String pointer with range syntax and converting the string into a literal, executed matched case.
Here is an example
fn main() {
let name = String::from("two");
match &name[..] {
"one" => println!("1"),
"two" => println!("2"),
"three" => println!("3"),
_ => println!("Default"),
}
}
Output:
2
The third way, typecast string object as &str
fn main() {
let name = String::from("two");
match &name as &str {
"one" => println!("1"),
"two" => println!("2"),
"three" => println!("3"),
_ => println!("Default"),
}
}