Debian Codegraph @

debian/missing-sources/derive_more-impl/doc/as_ref.md

raw symbols SCIP
1 # What `#[derive(AsRef)]` generates
2
3 Deriving `AsRef` generates one or more implementations of `AsRef`, each
4 corresponding to one of the fields of the decorated type.
5 This allows types which contain some `T` to be passed anywhere that an
6 `AsRef<T>` is accepted.
7
8
9
10
11 ## Newtypes and Structs with One Field
12
13 When `AsRef` is derived for a newtype or struct with one field, a single
14 implementation is generated to expose the underlying field.
15
16 ```rust
17 # use derive_more::AsRef;
18 #
19 #[derive(AsRef)]
20 struct MyWrapper(String);
21 ```
22
23 Generates:
24
25 ```rust
26 # struct MyWrapper(String);
27 impl AsRef<String> for MyWrapper {
28 fn as_ref(&self) -> &String {
29 &self.0
30 }
31 }
32 ```
33
34 It's also possible to use the `#[as_ref(forward)]` attribute to forward
35 to the `as_ref` implementation of the field. So here `SingleFieldForward`
36 implements all `AsRef` for all types that `Vec<i32>` implements `AsRef` for.
37
38 ```rust
39 # use derive_more::AsRef;
40 #
41 #[derive(AsRef)]
42 #[as_ref(forward)]
43 struct SingleFieldForward(Vec<i32>);
44
45 let item = SingleFieldForward(vec![]);
46 let _: &[i32] = (&item).as_ref();
47 ```
48
49 This generates code equivalent to:
50
51 ```rust
52 # struct SingleFieldForward(Vec<i32>);
53 impl<T: ?Sized> AsRef<T> for SingleFieldForward
54 where
55 Vec<i32>: AsRef<T>,
56 {
57 #[inline]
58 fn as_ref(&self) -> &T {
59 self.0.as_ref()
60 }
61 }
62 ```
63
64 Specifying concrete types, to derive impls for, is also supported via
65 `#[as_ref(<types>)]` attribute. These types can include both the type
66 of the field itself, and types for which the field type implements `AsRef`.
67
68 ```rust
69 # use derive_more::AsRef;
70 #
71 #[derive(AsRef)]
72 #[as_ref(str, [u8], String)]
73 struct Types(String);
74
75 let item = Types("test".to_owned());
76 let _: &str = item.as_ref();
77 let _: &[u8] = item.as_ref();
78 let _: &String = item.as_ref();
79 ```
80
81 > **WARNING**: When either the field type, or the specified conversion type,
82 > contains generic parameters, they are considered as the same type only if
83 > are named string-equally, otherwise are assumed as different types even
84 > when represent the same type in fact (type aliases, for example).
85 >
86 > ```rust
87 > # use derive_more::AsRef;
88 > #
89 > #[derive(AsRef)]
90 > #[as_ref(i32)] // generates `impl<T: AsRef<i32>> AsRef<i32> for Generic<T>`
91 > struct Generic<T>(T);
92 >
93 > #[derive(AsRef)]
94 > #[as_ref(T)] // generates `impl<T> AsRef<T> for Transparent<T>`
95 > struct Transparent<T>(T);
96 >
97 > #[derive(AsRef)]
98 > // #[as_ref(RenamedVec<T>)] // not supported, as types are not named string-equally
99 > struct Foo<T>(Vec<T>);
100 > type RenamedVec<T> = Vec<T>;
101 >
102 > #[derive(AsRef)]
103 > #[as_ref(RenamedString)] // generates `impl AsRef<RenamedString> for Bar`,
104 > struct Bar(String); // as generics are not involved
105 > type RenamedString = String;
106 > ```
107
108 Generating code like this is not supported:
109
110 ```rust
111 struct Generic<T>(T);
112
113 impl AsRef<i32> for Generic<i32> {
114 fn as_ref(&self) -> &i32 {
115 &self.0
116 }
117 }
118 ```
119
120
121
122
123 ## Structs with Multiple Fields
124
125 When `AsRef` is derived for a struct with more than one field (including tuple
126 structs), you must also mark one or more fields with the `#[as_ref]` attribute.
127 An implementation will be generated for each indicated field.
128
129 ```rust
130 # use derive_more::AsRef;
131 #
132 #[derive(AsRef)]
133 struct MyWrapper {
134 #[as_ref(str)]
135 name: String,
136 #[as_ref]
137 num: i32,
138 valid: bool,
139 }
140 ```
141
142 Generates:
143
144 ```rust
145 # struct MyWrapper {
146 # name: String,
147 # num: i32,
148 # valid: bool,
149 # }
150 impl AsRef<str> for MyWrapper {
151 fn as_ref(&self) -> &str {
152 self.name.as_ref()
153 }
154 }
155
156 impl AsRef<i32> for MyWrapper {
157 fn as_ref(&self) -> &i32 {
158 &self.num
159 }
160 }
161 ```
162
163
164 ### Tuples (not supported)
165
166 Only conversions that use a single field are possible with this derive.
167 Something like this wouldn't work, due to the nature of the `AsRef` trait
168 itself:
169
170 ```rust,compile_fail
171 # use derive_more::AsRef
172 #
173 #[derive(AsRef)]
174 #[as_ref((str, [u8]))]
175 struct MyWrapper(String, Vec<u8>)
176 ```
177
178 If you need to convert into a tuple of references, consider using the
179 [`Into`](crate::Into) derive with `#[into(ref)]`.
180
181
182 ### Skipping
183
184 Or vice versa: you can exclude a specific field by using `#[as_ref(skip)]` (or
185 `#[as_ref(ignore)]`). Then, implementations will be generated for non-indicated fields.
186
187 ```rust
188 # use derive_more::AsRef;
189 #
190 #[derive(AsRef)]
191 struct MyWrapper {
192 #[as_ref(skip)]
193 name: String,
194 #[as_ref(ignore)]
195 num: i32,
196 valid: bool,
197 }
198 ```
199
200 Generates:
201
202 ```rust
203 # struct MyWrapper {
204 # name: String,
205 # num: i32,
206 # valid: bool,
207 # }
208 impl AsRef<bool> for MyWrapper {
209 fn as_ref(&self) -> &bool {
210 &self.valid
211 }
212 }
213 ```
214
215
216 ### Coherence
217
218 Note that `AsRef<T>` may only be implemented once for any given type `T`.
219 This means any attempt to mark more than one field of the same type with
220 `#[as_ref]` will result in a compilation error.
221
222 ```rust,compile_fail
223 # use derive_more::AsRef;
224 #
225 // Error! Conflicting implementations of AsRef<String>
226 #[derive(AsRef)]
227 struct MyWrapper {
228 #[as_ref]
229 str1: String,
230 #[as_ref]
231 str2: String,
232 }
233 ```
234
235 Similarly, if some field is annotated with `#[as_ref(forward)]`, no other
236 field can be marked.
237
238 ```rust,compile_fail
239 # use derive_more::AsRef;
240 #
241 // Error! Conflicting implementations of `AsRef<i32>`
242 // note: upstream crates may add a new impl of trait `AsRef<i32>`
243 // for type `String` in future versions
244 #[derive(AsRef)]
245 struct ForwardWithOther {
246 #[as_ref(forward)]
247 str: String,
248 #[as_ref]
249 number: i32,
250 }
251 ```
252
253 Multiple forwarded impls with different concrete types, however, can be used.
254
255 ```rust
256 # use derive_more::AsRef;
257 #
258 #[derive(AsRef)]
259 struct Types {
260 #[as_ref(str)]
261 str: String,
262 #[as_ref([u8])]
263 vec: Vec<u8>,
264 }
265
266 let item = Types {
267 str: "test".to_owned(),
268 vec: vec![0u8],
269 };
270
271 let _: &str = item.as_ref();
272 let _: &[u8] = item.as_ref();
273 ```
274
275
276
277
278 ## Enums
279
280 Deriving `AsRef` for enums is not supported.