The Deref trait enables deref coercion, allowing a reference to a smart pointer (like &Box<T>) to be treated as a reference to the inner data (&T) without explicit dereferencing. This means you can pass smart pointers to functions expecting references, and the compiler automatically handles the conversion, preserving borrowing rules while simplifying syntax.
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 hello(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
let m = MyBox(String::from("Rust"));
hello(&m); // &MyBox<String> coerces to &String, then &str
}