Difference between str and String

Well, I wouldn’t bet on the compiler explaining this anytime soon, but the reference can give you all the details. I posted an explanation about why &String coerces to &str here, so please read through it:

The situation here very similar since &T implements Deref with Target = T ⟶ here, and thus &&T coerces to &T.


In case that isn’t clear, the & is not “optional” in the sense of “you kind of need it but it can be left implicit”. What OPs code example does is add a redundant & that doesn’t hurt because of the implicit de-referencing that reverses its effect. In my view, this situation it is more of an optional * or .deref() than an optional &.

Also, & is rarely optional in situations where you really need to create a reference. The only place I can think of is method call receivers, so that you wouldn’t need to write (&x).method() instead of x.method() when method takes a &self and x is not a reference already. If you’re also interested in more information about referencing and dereferencing of method receivers, you can read this page of the reference.

In the case of string literal, the literal itself already has type &'static str, that’s why you don’t need to write any &.

3 Likes