What is difference between &str and &str[..]

Hi am working through The Book and in the section on strings and concatenation it states

Rust uses a deref coercion , which here turns &s2 into &s2[..] . We’ll discuss deref coercion in more depth in Chapter 15

Can someone explain the difference please?

A deref coercion is when the compiler automatically turns one kind of reference into another. For example:

  • Deref coercion will automatically turn &String into &str.
  • Deref coercion will automatically turn &Vec<T> into &[T].

The list of deref coercions that can happen are defined using the Deref trait. This will also let you define deref coercions for your own types.

As for &s2[..], let's pull it apart:

  • The .. value. These two dots are short-hand for the RangeFull type. So, when you type .., this creates a RangeFull value.
  • The s2[..] syntax. This uses the indexing operators. It's equivalent to *s2.index(..). That is, you call the index method on s2 with a RangeFull as the argument.
  • The ampersand in &s2[..]. This creates a reference to the value you are indexing.

So in this case, since s2 is a String, you first index it using RangeFull, which gives you the entire string as a str. Then you add an ampersand, which gives you an &str.

So what's going on here, is that they're telling you that deref coercion on a String has the same effect as using RangeFull to get the entire string.

5 Likes

Very clear, thanks for taking the time and for the references (excuse the pun) to the docs :slightly_smiling_face:

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.