Deref and Wrapper Ergonomics
Make wrappers feel native.
The Ergonomics Problem
Wrapping a type in a newtype gains safety but loses convenience: suddenly you must write wrapper.0.method() everywhere and reimplement methods by hand.
The Deref trait can restore much of that ergonomics by letting the wrapper behave like the value it holds.
What Deref Does
Deref defines what *value produces and powers the . operator. When you call a method that the wrapper lacks, the compiler tries again on the deref target.
This automatic step is called deref coercion.
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T { &self.0 }
}All lessons in this course
- The Builder Pattern
- The Newtype Pattern
- Type-State Builders
- Deref and Wrapper Ergonomics