`Deref` lets a value expose a target through the `*` operator. Rust also uses it implicitly during method calls: a `Box<T>` can call methods on `T`, and a wrapper struct can call methods on the type it wraps. This is useful when a wrapper needs its own trait implementations without reimplementing every method of its inner value. section 10.6 section 7.2.1
impl<T> Deref for WrappedVec<T> {
type Target = Vec<T>; #1
fn deref(&self) -> &Self::Target {
&self.0 #2
}
}
A `WrappedVec<T>` containing a `Vec<T>` implements `Deref` by setting `Target` to `Vec<T>` and returning a reference to its inner field. Afterward, `wrapped_vec.iter()` can resolve to the vector’s method. section 7.2.2
That forwarding has limits. `Deref` supports access through a shared reference; it does not make a consuming method such as `into_iter()` available on the wrapper. Provide a wrapper method that consumes `self` and calls `self.0.into_iter()` instead. Methods needing mutable access require `DerefMut`. section 7.2.2
Listing 10.9 Demonstrating Deref coercion
use std::ops::Deref;
struct Person(String, String, u32); #1
impl Deref for Person {
type Target = String; #2
fn deref(&self) -> &Self::Target {
&self.0 #3
}
}
fn main() {
let ferris = Person("Ferris".to_string(), "Bueller".to_string(), 17);
println!("Hello, {}!", *ferris); #4
println!("The length of a person is {}", ferris.len()); #5
}
A tuple struct holding a first name, last name, and age can dereference to its first-name `String`. Then `*ferris` yields the name and `ferris.len()` calls `String::len()`. The code works, but making a person appear to be a string obscures what `len()` means; a named `first_name_len()` method is clearer. section 10.6
Use `Deref` when behaving like the wrapped type is the point, not as a substitute for polymorphism. For shared behavior across different types, prefer traits and generics; when callers only need the inner value, consider an explicit accessor. A `Vec<Box<dyn Animal>>` illustrates trait objects handling different animal types without using `Deref` to imitate inheritance. section 10.6 section 10.10

