Deref 是一个内置trait,也是一个操作符,例如当我们使用Box 变量的时候,我们不用手动deref它,这就是因为Box实现了Deref这个trait也就是当 .
的时候自动的deref了
自定义Deref
#[derive(Debug)]
struct Selector<T> {
elements: Vec<T>,
current: usize,
}
impl<T> Deref for Selector<T> {
type Target = T;
fn deref(&self) -> &T {
&self.elements[self.current]
}
}
impl<T> DerefMut for Selector<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.elements[self.current]
}
}
fn main() {
let mut s = Selector {
elements: vec!['x', 'y', 'z'],
current: 2,
};
assert_eq!(*s, 'z');
assert!(s.is_alphabetic()); //this is because deref coercions https://doc.rust-lang.org/book/ch15-02-deref.html
*s = 'w';
assert_eq!(*s, 'w');
}