简单的 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");
}
使用指针类型(如 Box 或 Arc)时,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]
}