Newtype Deref Pattern
You wrap a type (e.g., f64, i64) in a “newtype” (a single-field struct) and implement the Deref trait to delegate access to the inner value, to combine type-safety with ergonomic access:
- the wrapper distinguish the type
- users can access the inner value using the
*my_typederef syntax
use std::ops::Deref;
pub struct Kilometers(pub f64);
impl Deref for Kilometers {
type Target = f64;
fn deref(&self) -> &Self::Target {
&self.0
}
}