点运算符

Rust 中的 . 运算符带来了很多魔力! 使用 . 时,编译器将插入尽可能多的*s(解除引用操作),以便在 deref中找到该方法。由于这在编译时发生,因此找不到该方法的运行时成本。

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);

自动解除引用也适用于实现 std::ops::Deref 特性的任何类型。

let vec = vec![1, 2, 3];
let iterator = vec.iter();

这里,iter 不是 Vec<T> 的方法,而是 [T] 的方法。它的工作原理是因为 Vec<T>Target=[T] 实现Deref,当*操作符(编译器可以在一个时间内插入)时,Vec<T> 会转换为 [T]