Rust Deref
and DerefMut
Those two traits are for dereferencing operations like *v
. They are often used by compiler implicitly (which is called Deref coercion).
The Rust documentation recommends to only implement those traits for smart pointers to minimize confusing. Other uses, such as using using Deref to mimic polymorphism, are considered anti-patterns.
Those traits should also never fail.
Example:
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
Rust compiler will then transform *y
into *(y.deref())
.