Deref 胁迫
鉴于 T
和 U
两种类型,当且仅当 T
实现 Deref<Target=U>
时,&T
将强制(隐式转换)为 &U
这允许我们做这样的事情:
fn foo(a: &[i32]) {
// code
}
fn bar(s: &str) {
// code
}
let v = vec![1, 2, 3];
foo(&v); // &Vec<i32> coerces into &[i32] because Vec<T> impls Deref<Target=[T]>
let s = "Hello world".to_string();
let rc = Rc::new(s);
// This works because Rc<T> impls Deref<Target=T> ∴ &Rc<String> coerces into
// &String which coerces into &str. This happens as much as needed at compile time.
bar(&rc);