Deref 是一个内置trait,也是一个操作符,例如当我们使用Box 变量的时候,我们不用手动deref它,这就是因为Box实现了Deref这个trait也就是当 . 的时候自动的deref了

自定义Deref

  1. #[derive(Debug)]
  2. struct Selector<T> {
  3. elements: Vec<T>,
  4. current: usize,
  5. }
  6. impl<T> Deref for Selector<T> {
  7. type Target = T;
  8. fn deref(&self) -> &T {
  9. &self.elements[self.current]
  10. }
  11. }
  12. impl<T> DerefMut for Selector<T> {
  13. fn deref_mut(&mut self) -> &mut T {
  14. &mut self.elements[self.current]
  15. }
  16. }
  17. fn main() {
  18. let mut s = Selector {
  19. elements: vec!['x', 'y', 'z'],
  20. current: 2,
  21. };
  22. assert_eq!(*s, 'z');
  23. assert!(s.is_alphabetic()); //this is because deref coercions https://doc.rust-lang.org/book/ch15-02-deref.html
  24. *s = 'w';
  25. assert_eq!(*s, 'w');
  26. }