References and the dot operator
Rust will do de-referencing for free when we call methods with the dot(.
) operator
So, take the code below for example, it will cause an error as type references have a type different for the referenced type, which is why we need de-referencing with *
to get to the type before operations like comparison can take place.
let name = "Adetunji".to_string();
let other_name = &name;
println!("{}", name == other_name);
But dereferencing will work here,
let name = "Adetunji".to_string();
let other_name = &name;
println!("{}", name == *other_name);
The dot operation help us bypass dereferencing ourselves, it handles it for us. That why the code below will work. It dereferencing to the original types regardless if you have many references like this &&&&&name
let name = "Adetunji".to_string();
let other_name = &&&name;
println!("{}", other_name.is_empty());