The Deref trait enables smart pointers to behave like regular references by allowing the compiler to automatically dereference them when accessing fields or calling methods. Implementing Deref on a custom smart pointer type lets you use the * operator or access methods directly on the pointer without explicit dereferencing, creating ergonomic syntax similar to standard references.
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
fn main() {
let x = MyBox(5);
println!("{}", *x); // Automatically calls deref()
}