Deref lets a type act like a reference to a value it holds. Implementing it allows the `*` operator to reach that value and lets method calls find methods on the held type. This is useful for a wrapper that adds its own behavior without exposing its inner field directly. section 15.3.1 section 15.3.2 section 15.3
From a compiler error to a dereference
Suppose `HoldsANumber(u8)` contains `20`. Unlike a `Box`, it cannot initially be used as `*my_number`: the compiler says `HoldsANumber` cannot be dereferenced. Implementing `Deref` fixes that. Set `type Target = u8`, then make `deref(&self)` return `&self.0`. Now `*my_number + 20` produces `40` without writing `my_number.0`. section 15.3.1 section 15.3.2
use std::ops::Deref;
struct HoldsANumber(u8);
impl HoldsANumber {
fn prints_the_number_times_two(&self) {
println!("{}", self.0 * 2);
}
}
impl Deref for HoldsANumber {
type Target = u8;
fn deref(&self) -> &Self::Target {
&self.0
}
}
fn main() {
let my_number = HoldsANumber(20);
println!("{:?}", my_number.checked_sub(100)); #1
my_number.prints_the_number_times_two(); #2
}
The complete example puts an original method on `HoldsANumber` and uses `checked_sub()` from the inner `u8`. The call returns `None` when subtracting 100 from 20 would go below the range of `u8`. section 15.3.2
Deref provides immutable access, not permission to change the inner value. Even with `let mut my_number`, assigning through `*my_number` fails; the compiler points to `DerefMut` as the missing trait. section 15.3.2
Use Deref when the type really behaves like a smart pointer to its target. Making a game character dereference to its hit-point number may compile, but `*character` hides what the operation means. A named method such as `get_hp()` or `change_hp()` is clearer. section 15.3.4

