How to Match a String Against String Literals in Rust

1. Overview

As we know, we can represent text as a String or string literal (&str) in Rust. A String is a growable, mutable, owned string type, while a string literal is an immutable reference to a sequence of UTF-8 bytes.

In this article, we’ll delve into the basics of String and string literals. Additionally, we’ll see how to match a String with string literals using the as_str() method.

2. Understanding String and String Literals

A string is a heap-allocated, dynamically resizable data structure that can store any valid UTF-8 sequence of bytes. Under the hood, a string is implemented as a vector of bytes (Vec<u8>).

Unlike C-style strings, String values are not null-terminated. Its values can be modified using push_str() to append data.

On the other hand, a string literal &str is an immutable reference to a sequence of UTF-8 bytes. String literals are stored in the program’s data segment or on the stack, and we cannot modify the data they point to directly.

However, we can create a new &str by taking a slice of a String using indexing or methods like as_str().

3. Simulating Problem

Let’s assume we intend to match a given word of String type to a string literal:

let cup = String::from("cup");
match cup {
    "bat" => println!("0"),
    "ball" => println!("1"),
    "cup" => println!("2"),
    _ => println!("something else!"),
}

This will result in a mismatch error because the match expression expects a &str but the cup is a String:

error[E0308]: mismatched types
--> src/main.rs:5:9
 match cup {
| --- this expression has type `String`
5 | "bat" => println!("0"),
| ^^^^^ expected `String`, found `&str`

The error message indicates that we are trying to match between two different types.

4. Using as_str()

The as_str() method helps extract an immutable string slice &str from a String. To solve the problem in view, we need to match the string slice instead of the entire String:

let cup = String::from("cup");
match cup.as_str() {
    "bat" => println!("0"),
    "ball" => println!("1"),
    "cup" => println!("2"),
    _ => println!("something else!"),
}

In the code above, we use the as_str() method to convert from String to &str. All options in the match patterns are &str. Using the as_str() method convert the type of cup to &str().

4. Conclusion

In this short article, we learn how to convert from String to string literal to avoid mismatch type errors. We use the as_str() method to convert string to string slice because our match pattern expects a string literal.