點運算子

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]