Debian Codegraph @

third_party/rust/derive_more-impl/doc/deref.md

raw
1 # Using `#[derive(Deref)]`
2
3 Deriving `Deref` only works for a single field of a struct.
4 It's possible to use it in two ways:
5
6 1. Dereferencing to the field, i.e. like if your type was a reference type.
7 2. Doing a dereference on the field, for when the field itself is a reference type like `&` and `Box`.
8
9 With `#[deref]` or `#[deref(ignore)]` it's possible to indicate the field that
10 you want to derive `Deref` for.
11
12
13
14
15 ## Example usage
16
17 ```rust
18 # use derive_more::Deref;
19 #
20 #[derive(Deref)]
21 struct Num {
22 num: i32,
23 }
24
25 #[derive(Deref)]
26 #[deref(forward)]
27 struct MyBoxedInt(Box<i32>);
28
29 // You can specify the field you want to derive `Deref` for.
30 #[derive(Deref)]
31 struct CoolVec {
32 cool: bool,
33 #[deref]
34 vec: Vec<i32>,
35 }
36
37 let num = Num{num: 123};
38 let boxed = MyBoxedInt(Box::new(123));
39 let cool_vec = CoolVec{cool: true, vec: vec![123]};
40 assert_eq!(123, *num);
41 assert_eq!(123, *boxed);
42 assert_eq!(vec![123], *cool_vec);
43 ```
44
45
46
47
48 ## Structs
49
50 When deriving a non-forwarded `Deref` for a struct:
51
52 ```rust
53 # use derive_more::Deref;
54 #
55 #[derive(Deref)]
56 struct CoolVec {
57 cool: bool,
58 #[deref]
59 vec: Vec<i32>,
60 }
61 ```
62
63 Code like this will be generated:
64
65 ```rust
66 # struct CoolVec {
67 # cool: bool,
68 # vec: Vec<i32>,
69 # }
70 impl ::core::ops::Deref for CoolVec {
71 type Target = Vec<i32>;
72 #[inline]
73 fn deref(&self) -> &Self::Target {
74 &self.vec
75 }
76 }
77 ```
78
79 When deriving a forwarded `Deref` for a struct:
80
81 ```rust
82 # use derive_more::Deref;
83 #
84 #[derive(Deref)]
85 #[deref(forward)]
86 struct MyBoxedInt(Box<i32>);
87 ```
88
89 Code like this will be generated:
90
91 ```rust
92 # struct MyBoxedInt(Box<i32>);
93 impl ::core::ops::Deref for MyBoxedInt {
94 type Target = <Box<i32> as ::core::ops::Deref>::Target;
95 #[inline]
96 fn deref(&self) -> &Self::Target {
97 <Box<i32> as ::core::ops::Deref>::deref(&self.0)
98 }
99 }
100 ```
101
102
103
104
105 ## Enums
106
107 Deriving `Deref` is not supported for enums.