The .
operator in Rust comes with a lot of magic! When you use .
, the compiler will insert as many *
s (dereferencing operations) necessary to find the method down the deref "tree". As this happens at compile time, there is no runtime cost of finding the method.
let mut name: String = "hello world".to_string();
// no deref happens here because push is defined in String itself
name.push('!');
let name_ref: &String = &name;
// Auto deref happens here to get to the String. See below
let name_len = name_ref.len();
// You can think of this as syntactic sugar for the following line:
let name_len2 = (*name_ref).len();
// Because of how the deref rules work,
// you can have an arbitrary number of references.
// The . operator is clever enough to know what to do.
let name_len3 = (&&&&&&&&&&&&name).len();
assert_eq!(name_len3, name_len);
Auto dereferencing also works for any type implementing std::ops::Deref
trait.
let vec = vec![1, 2, 3];
let iterator = vec.iter();
Here, iter
is not a method of Vec<T>
, but a method of [T]
. It works because Vec<T>
implements Deref
with Target=[T]
which lets Vec<T>
turn into [T]
when dereferenced by the *
operator (which the compiler may insert during a .
).