解引用的trait
实现Deref trait允许我们重载解引用运算符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| let a: A = A::new(); let b = &a; let c = *b;
fn main() { let x = 5; let y = &x; assert_eq!(5,x); assert_eq!(5,*y);
let z = Box::new(x);
assert_eq!(5,*z);
}
|
解引用Deref trait的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| use std::ops::Deref; struct MyBox<T>(T);
impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } fn main() { let x = 5; let y = MyBox::new(x);
assert_eq!(5,x); assert_eq!(5,*y);
}
|
解引用的强制多态
Deref为String实现了强制多态,在使用&String的时候,强制多态转换为&str
解引用多态和可变性的交互:
- 当T:Deref<Target=U>时,从&T到&U
- 当T: DerefMut<Target=U>时,从&mut T到&mut U
- 当T: Deref<Target=U>时,从&mut T到& U
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| use std::ops::Deref; struct MyBox<T>(T);
impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { &self.0 } }
fn hello(name: &str) { println!("Hello, {}",name); } fn main() { let m = MyBox::new(String::from("Rust")); hello(&m); }
|