Deref coercion lets a wrapper behave like its dereference target for method calls. Implement `Deref` with a `Target` type and a `deref` method returning a reference to the wrapped value; the compiler can then resolve methods on that target. section 7.2.2 section 10.6
impl<T> Deref for WrappedVec<T> {
type Target = Vec<T>; #1
fn deref(&self) -> &Self::Target {
&self.0 #2
}
}
This implementation makes `Vec` methods such as `iter()` available through `WrappedVec`. section 7.2.2
Keep the method-call convenience distinct from these limitations:
- Methods requiring `&mut self` need `DerefMut` on the wrapper. section 7.2.2
- Deref does not expose methods that consume the wrapped value, such as `into_iter()`; provide an appropriate wrapper method for those operations. section 7.2.2
Convenience is not polymorphism
A `Person` wrapping strings can use `ferris.len()` through Deref coercion, but the call obscures that it measures the first name. A clearly named method is easier to understand. Avoid using Deref to imitate polymorphism; use traits and generics, trait objects, or an explicit method that returns the inner value when appropriate. section 10.6 section 10.6
