Search code examples
stringrustdereference

Why does applying & to a String return a &str?


In this example code from the Rust documentation:

fn takes_str(s: &str) { }

let s = String::from("Hello");

takes_str(&s);

What exactly is going on behind the scenes that causes &s to become a &str instead of a &String? The documentation seems to suggest that there's some dereferencing going on, but I thought * was for dereferencing, not &?


Solution

  • What's going on here is called deref coercions. These allow references to types that implement the Deref trait to be used in place of references to other types. As your example shows, &String can be used anywhere a &str is required, because String implements Deref to str.