&str and &String

#1

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?

0 Likes

#2

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

#3

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

#4

Maybe this helps too

2 Likes

#5

The mechanism isn’t explained until later, because at this point of the book, we haven’t learned enough Rust to understand it https://doc.rust-lang.org/book/ch15-02-deref.html#treating-a-type-like-a-reference-by-implementing-the-deref-trait

1 Like