References vs slices of the whole string

Lets say we have a string:

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

Is this

let slice = &s[..];

the same as this

let ref = &s;


I know that both slice and ref are pointers that point to the byte at index 0 of s but is there any difference "under the hood"?

ref (if you could name the variable that, which you can't because ref is a keyword) has type &String, which as far as memory layout goes is a pointer to a pointer to bytes, unlike &str which is a pointer to bytes. (Both have a length, too.)

However, Rust will automatically coerce &String to &str when you try to use it as one, in most cases (such as passing it to another function or calling a method of it), so this is invisible until you start having more explicit types involved.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.