簡單的 Deref 示例

Deref 有一個簡單的規則:如果你有一個型別 T 並且它實現了 Deref<Target=F>,那麼 &T 強制到 &F,編譯器會根據需要多次重複這個以獲得 F,例如:

fn f(x: &str) -> &str { x }
fn main() {
    // Compiler will coerce &&&&&&&str to &str and then pass it to our function
    f(&&&&&&&"It's a string"); 
}

使用指標型別(如 BoxArc)時,Deref 強制特別有用,例如:

fn main() {
    let val = Box::new(vec![1,2,3]);
    // Now, thanks to Deref, we still 
    // can use our vector method as if there wasn't any Box
    val.iter().fold(0, |acc, &x| acc + x ); // 6
    // We pass our Box to the function that takes Vec,
    // Box<Vec> coerces to Vec
    f(&val)
}

fn f(x: &Vec<i32>) {
    println!("{:?}", x) // [1,2,3]
}