Deref — dereference operator overloading. DerefMut — mutable deref.
Implementation:
1use std::ops::{Deref, DerefMut};23struct MyBox<T>(T);45impl<T> Deref for MyBox<T> {6 type Target = T;78 fn deref(&self) -> &T {9 &self.010 }11}1213impl<T> DerefMut for MyBox<T> {14 fn deref_mut(&mut self) -> &mut T {15 &mut self.016 }17}
Deref coercion:
1fn greet(name: &str) {2 println!("Hello, {}!", name);3}45let name = MyBox::new(String::from("Alice"));6greet(&name); // MyBox<String> -> String -> str
Key: Deref for smart pointer coercion.