Using #[derive(Deref)]
Deriving Deref
only works for a single field of a struct.
It’s possible to use it in two ways:
- Dereferencing to the field, i.e. like if your type was a reference type.
- Doing a dereference on the field, for when the field itself is a reference type like
&
andBox
.
With #[deref]
or #[deref(ignore)]
it’s possible to indicate the field that
you want to derive Deref
for.
1 Example usage
#[derive(Deref)] struct Num { num: i32, } #[derive(Deref)] #[deref(forward)] struct MyBoxedInt(Box<i32>); // You can specify the field you want to derive Deref for #[derive(Deref)] struct CoolVec { cool: bool, #[deref] vec: Vec<i32>, } fn main() { let num = Num{num: 123}; let boxed = MyBoxedInt(Box::new(123)); let cool_vec = CoolVec{cool: true, vec: vec![123]}; assert_eq!(123, *num); assert_eq!(123, *boxed); assert_eq!(vec![123], *cool_vec); }
2 Structs
When deriving a non-forwarded Deref
for a struct:
#[derive(Deref)] struct CoolVec { cool: bool, #[deref] vec: Vec<i32>, }
Code like this will be generated:
impl ::core::ops::Deref for CoolVec { type Target = Vec<i32>; #[inline] fn deref(&self) -> &Self::Target { &self.vec } }
When deriving a forwarded Deref
for a struct:
#[derive(Deref)] #[deref(forward)] struct MyBoxedInt(Box<i32>);
Code like this will be generated:
impl ::core::ops::Deref for MyBoxedInt { type Target = <Box<i32> as ::core::ops::Deref>::Target; #[inline] fn deref(&self) -> &Self::Target { <Box<i32> as ::core::ops::Deref>::deref(&self.0) } }
3 Enums
Deriving Deref
is not supported for enums.