&str and &String

https://doc.rust-lang.org/book/ch04-03-slices.html

I am not understanding how come you can put a String variable into a funciton that accepts &str?

You are right to be confused: &String is not the same type as &str. But there is a convenient bit of magic called 'deref-coercion' where a &String automatically gets converted into &str. It also kicks in when you call a &str method on a String.

It's one of the few places where Rust does something implicitly like this.

4 Likes

from https://doc.rust-lang.org/std/ops/trait.Deref.html

If T implements Deref<Target = U>, and x is a value of type T, then:

In immutable contexts, *x on non-pointer types is equivalent to *Deref::deref(&x).
Values of type &T are coerced to values of type &U
T implicitly implements all the (immutable) methods of the type U.

and
https://doc.rust-lang.org/src/alloc/string.rs.html#2038-2045

impl ops::Deref for String {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        unsafe { str::from_utf8_unchecked(&self.vec) }
    }
}

&String will coerced to &str

2 Likes

Maybe this helps too

https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-to-a-string-string-vec-vec-or

2 Likes

The mechanism isn't explained until later, because at this point of the book, we haven't learned enough Rust to understand it Treating Smart Pointers Like Regular References with the Deref Trait - The Rust Programming Language

1 Like