Alex's Blog

Rust's strings

Another day, another expected `&str`, found struct `String` error somewhere in my code. Since it's Sunday, I can take a few minutes to look into rust's strings (again) and jolt down some notes for future me.

&str and String

The two main types used to store human readable strings in rust are &str and String. They are pretty well explained in the Rust By Example book, but basically:

Converting from one to another is easily possible as

String dereferencing

String implements Deref<Target = str>, meaning that through the power of Deref coercion a &String reference can be used in places where a &str is expected. This converstion happens automatically when references are passed to types which implement the appropiate Deref trait.

Automatic reference level reduction

In addition, due to how Deref coercion works, the compiler can also automatically remove reference levels in certain places. For example, the following code would work as normal (see rust playground):

fn test(a: &str) {
    println!("{}", a)

fn main() {
    let s: &str = "Hello world!";
    // and so on...