0
let s1 = String::from("hello world.");
let r1 = &s1;
let sl1 = &s1[..];
let sl2 = &r1[..];
let sl3 = r1[..];
println!("{}", sl3);

What is the difference between sl1 and sl2, and why sl3 is invalid? Isn't r1 a reference already, why need &?

Matthieu M.
  • 251,718
  • 39
  • 369
  • 642
sunfy
  • 1,867
  • 11
  • 17
  • Would the answers to [this question](https://stackoverflow.com/questions/27879161/what-is-the-return-type-of-the-indexing-operation-on-a-slice) also answer yours? – Matthieu M. Dec 14 '17 at 14:04
  • Regarding the question about the difference between `sl1` and `sl2`, there isn't any. Both cause the `String` to be dereferenced to a slice, and the slice is then indexed with a range. See also https://stackoverflow.com/q/28519997/279627 – Sven Marnach Dec 14 '17 at 14:17

1 Answers1

1

The compiler dereferences the output of Index::index when desugaring the indexing syntax [] (see related question and its answers). Using explicit type annotations, the types of the bindings are thus as follows:

let r1: &str = &s1;
let sl1: &str = &s1[..];
let sl2: &str = &r1[..];
let sl3: str = r1[..];

str, being an unsized type, cannot be put on the stack and therefore cannot be used as the type for a local variable binding sl3, hence the compile error.

EvilTak
  • 5,368
  • 17
  • 32