How to match a String against string literals in Rust example
This tutorial explores comparing string objects with string literals in Rust.
String literals and string objects are distinct object types in Rust, with string literals being declared as string slices.
String literals are string slices that can be declared.
let name = "one";
String objects can be created as follows:
let name1 = String::from("one");
Rust String Matching with String Literals
Rust provides pattern matching akin to a switch statement in Java, enabling the matching of an expression with a set of values and executing the corresponding case.
Match expressions and case expressions must align; otherwise, a mismatched type error occurs.
String objects can be converted to string literals (&str
) in multiple ways for comparison with string literals or slices.
One approach utilizes the match construct with as_str()
, converting the String object to a string literal using the as_str()
method, allowing for matching against multiple cases.
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
Another method involves accessing the String’s pointer with range syntax and converting the string into a literal before executing the 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 approach entails typecasting the string object directly as &str
.
fn main() {
let name = String::from("two");
match &name as &str {
"one" => println!("1"),
"two" => println!("2"),
"three" => println!("3"),
_ => println!("Default"),
}
}