The Deref trait allows custom smart pointer types to be treated like regular references by defining how to access the inner data. Implementing Deref enables dereferencing coercion, letting you call methods on the inner value directly without manual dereferencing.
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); // Works because of Deref
}