Matching Strings against String Literals in Rust

Alex Garella

18th July 2023

In this blog post, we'll be exploring how to match String against string literals in Rust.

In Rust, string comparison is fairly straightforward when comparing literals, but matching a String object against string literals can be a little tricky. Here, we'll use the match statement, which is similar to a switch-case in other languages.

Below is a code snippet demonstrating a simple match operation with string literals:

fn main() { let my_string = "hello"; match my_string { "hello" => println!("Hello, world!"), "goodbye" => println!("Goodbye, world!"), _ => println!("Neither hello nor goodbye!"), } }

The above code works perfectly well because my_string is a string literal (str). However, if my_string is a String object, this code will not compile. The primary reason is that String and str are two different types in Rust. Check out our blog post about the differences here.

So how do we match a String object with a string literal?

We can achieve this using the as_str() method that converts a String object into str.

fn main() { let my_string: String = String::from("hello"); match my_string.as_str() { "hello" => println!("Hello, world!"), "goodbye" => println!("Goodbye, world!"), _ => println!("Neither hello nor goodbye!"), } }

In the above code, the as_str() function is used to convert my_string (a String object) into a string slice (str), which can then be compared with string literals.

But what if we want to compare with case-insensitive matching?

To achieve this, you could convert both sides to lowercase using the to_lowercase() method, like so:

fn main() { let my_string: String = String::from("HELLO"); match my_string.to_lowercase().as_str() { "hello" => println!("Hello, world!"), "goodbye" => println!("Goodbye, world!"), _ => println!("Neither hello nor goodbye!"), } }

In this example, regardless of the case of the my_string value, if it is "hello" or "goodbye", it will match the appropriate case.

Remember that Rust's match keyword requires all possible cases to be handled. The _ is a catch-all pattern that matches 'anything else'.

And that's how you can match String against string literals in Rust. This feature can be particularly useful for parsing strings, implementing command-line interfaces, and more. As always, the key to Rust is understanding its strict, yet powerful type system. Happy coding!

Subscribe to receive the latest Rust jobs in your inbox

Receive a weekly overview of Rust jobs by subscribing to our mailing list

© 2024 RustJobs.dev, All rights reserved.