In general, &*
means to first dereference (*
) and then reference (&
) a value. In many cases, this would be silly, as we'd end up at the same thing.
However, Rust has deref coercions. Combined with the Deref
and DerefMut
traits, a type can dereference to a different type!
This is useful for String
s as that means that they can get all the methods from str
, it's useful for Vec<T>
as it gains the methods from [T]
, and it's super useful for all the smart pointers, like Box<T>
, which will have all the methods of the contained T
!
Following the chain for String
:
String --deref--> str --ref--> &str
Does not the &
mean we are taking its reference, then using the *
to dereference it?
No, your order of operations is backwards. *
and &
associate to the right. In this example, dereferencing is first, then referencing.
I think now you can do this &addr_string
(from a comment)
Sometimes, this will do the same thing. See What are Rust's exact auto-dereferencing rules? for the full details, but yes, a &String
can be passed to a function that requires a &str
. There are still times where you need to do this little dance by hand. The most common I can think of is:
let name: Option<String> = Some("Hello".to_string());
let name2: Option<&str> = name.as_ref().map(|s| &**s);
You'll note that we actually dereference twice:
&String -->deref--> String --deref--> str --ref--> &str
Although this case can now be done with name.as_ref().map(String::as_str);