Debian Codegraph @

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

raw symbols SCIP
1 # What `#[derive(Display)]` generates
2
3 Deriving `Display` will generate a `Display` implementation, with a `fmt`
4 method that matches `self` and each of its variants. In the case of a struct or union,
5 only a single variant is available, and it is thus equivalent to a simple `let` statement.
6 In the case of an enum, each of its variants is matched.
7
8 For each matched variant, a `write!` expression will be generated with
9 the supplied format, or an automatically inferred one.
10
11 You specify the format on each variant by writing e.g. `#[display("my val: {}", some_val * 2)]`.
12 For enums, you can either specify it on each variant, or on the enum as a whole.
13
14 For variants that don't have a format specified, it will simply defer to the format of the
15 inner variable. If there is no such variable, or there is more than 1, an error is generated.
16 The only exception are unit variants, for these the name of the variant will be used if no
17 format is specified. This can be controlled with the
18 [`#[display(rename_all = "...")]` attribute](#The-`rename_all`-attribute).
19
20
21
22
23 ## The format of the format
24
25 You supply a format by attaching an attribute of the syntax: `#[display("...", args...)]`.
26 The format supplied is passed verbatim to `write!`.
27
28 The variables available in the arguments is `self` and each member of the
29 struct or enum variant, with members of tuple structs being named with a
30 leading underscore and their index, i.e. `_0`, `_1`, `_2`, etc. Due to
31 ownership/lifetime limitations the member variables are all references to the
32 fields, except when used directly in the format string. For most purposes this
33 detail doesn't matter, but it is quite important when using `Pointer`
34 formatting. If you don't use the `{field:p}` syntax, you have to dereference
35 once to get the address of the field itself, instead of the address of the
36 reference to the field:
37
38 ```rust
39 # use derive_more::with_trait::Display;
40 #
41 #[derive(Display)]
42 #[display("{field:p} {:p}", *field)]
43 struct RefInt<'a> {
44 field: &'a i32,
45 }
46
47 let a = &123;
48 assert_eq!(format!("{}", RefInt{field: &a}), format!("{a:p} {:p}", a));
49 ```
50
51
52 ### Other formatting traits
53
54 The syntax does not change, but the name of the attribute is the snake case version of the trait.
55 E.g. `Octal` -> `octal`, `Pointer` -> `pointer`, `UpperHex` -> `upper_hex`.
56
57 Note, that `Debug` has a slightly different API and semantics, described in its docs, and so,
58 requires a separate `debug` feature.
59
60
61 ### Generic data types
62
63 When deriving `Display` (or other formatting trait) for a generic struct/enum, all generic type
64 arguments used during formatting are bound by respective formatting trait.
65 Bounds can only be inferred this way if a field is used directly in the interpolation.
66
67 E.g., for a structure `Foo` defined like this:
68 ```rust
69 # use derive_more::Display;
70 #
71 # trait Trait { type Type; }
72 #
73 #[derive(Display)]
74 #[display("{a} {b} {c:?} {d:p}")]
75 struct Foo<'a, T1, T2: Trait, T3> {
76 a: T1,
77 b: <T2 as Trait>::Type,
78 c: Vec<T3>,
79 d: &'a T1,
80 }
81 ```
82
83 The following where clauses would be generated:
84 * `T1: Display`
85 * `<T2 as Trait>::Type: Display`
86 * `Vec<T3>: Debug`
87 * `&'a T1: Pointer`
88
89
90 ### Custom trait bounds
91
92 Sometimes you may want to specify additional trait bounds on your generic type parameters, so that they
93 could be used during formatting. This can be done with a `#[display(bound(...))]` attribute.
94
95 `#[display(bound(...))]` accepts code tokens in a format similar to the format
96 used in angle bracket list (or `where` clause predicates): `T: MyTrait, U: Trait1 + Trait2`.
97
98 `#[display("fmt", ...)]` arguments are parsed as an arbitrary Rust expression and passed to generated
99 `write!` as-is, it's impossible to meaningfully infer any kind of trait bounds for generic type parameters
100 used this way. That means that you'll **have to** explicitly specify all the required trait bounds of the
101 expression. Either in the struct/enum definition, or via `#[display(bound(...))]` attribute.
102
103 Explicitly specified bounds are added to the inferred ones. Note how no `V: Display` bound is necessary,
104 because it's inferred already.
105
106 ```rust
107 # use derive_more::with_trait::Display;
108 #
109 # trait MyTrait { fn my_function(&self) -> i32; }
110 #
111 #[derive(Display)]
112 #[display(bound(T: MyTrait, U: Display))]
113 #[display("{} {} {}", a.my_function(), b.to_string().len(), c)]
114 struct MyStruct<T, U, V> {
115 a: T,
116 b: U,
117 c: V,
118 }
119 ```
120
121
122 ### Transparency
123
124 If the `#[display("...", args...)]` attribute is omitted, the implementation transparently delegates to the format
125 of the inner type, so all the additional [formatting parameters][1] do work as expected:
126 ```rust
127 # use derive_more::Display;
128 #
129 #[derive(Display)]
130 struct MyInt(i32);
131
132 assert_eq!(format!("{:03}", MyInt(7)), "007");
133 ```
134
135 If the `#[display("...", args...)]` attribute is specified and can be trivially substituted with a transparent
136 delegation call to the inner type, then additional [formatting parameters][1] will work too:
137 ```rust
138 # use derive_more::Display;
139 #
140 #[derive(Display)]
141 #[display("{_0:o}")] // the same as calling `Octal::fmt()`
142 struct MyOctalInt(i32);
143
144 // so, additional formatting parameters do work transparently
145 assert_eq!(format!("{:03}", MyOctalInt(9)), "011");
146
147 #[derive(Display)]
148 #[display("{_0:02b}")] // cannot be trivially substituted with `Binary::fmt()`,
149 struct MyBinaryInt(i32); // because of specified formatting parameters
150
151 // so, additional formatting parameters have no effect
152 assert_eq!(format!("{:07}", MyBinaryInt(2)), "10");
153 ```
154
155 If, for some reason, transparency in trivial cases is not desired, it may be suppressed explicitly
156 either with the [`format_args!()`] macro usage:
157 ```rust
158 # use derive_more::Display;
159 #
160 #[derive(Display)]
161 #[display("{}", format_args!("{_0:o}"))] // `format_args!()` obscures the inner type
162 struct MyOctalInt(i32);
163
164 // so, additional formatting parameters have no effect
165 assert_eq!(format!("{:07}", MyOctalInt(9)), "11");
166 ```
167 Or by adding [formatting parameters][1] which cause no visual effects:
168 ```rust
169 # use derive_more::Display;
170 #
171 #[derive(Display)]
172 #[display("{_0:^o}")] // `^` is centering, but in absence of additional width has no effect
173 struct MyOctalInt(i32);
174
175 // and so, additional formatting parameters have no effect
176 assert_eq!(format!("{:07}", MyOctalInt(9)), "11");
177 ```
178
179
180 ### Shared enum format
181
182 Enums can have shared top-level `#[display("...", args...)]` attribute. Depending on its contents,
183 it can act either as a default format or a wrapping one.
184
185 #### Wrapping enum format
186
187 To act as a wrapping format, the shared top-level `#[display("...", args...)]` attribute should
188 contain at least one special `{_variant}` placeholder, which is then replaced by the format string
189 that's provided (or inferred) on the variant.
190 ```rust
191 # use derive_more::Display;
192 #
193 #[derive(Display)]
194 #[display("Variant: {_variant} & {}", _variant)]
195 enum Enum {
196 #[display("A {_0}")]
197 A(i32),
198 B { field: i32 },
199 #[display("c")]
200 C,
201 }
202
203 assert_eq!(Enum::A(1).to_string(), "Variant: A 1 & A 1");
204 assert_eq!(Enum::B { field: 2 }.to_string(), "Variant: 2 & 2");
205 assert_eq!(Enum::C.to_string(), "Variant: c & c");
206 ```
207
208 #### Default enum format
209
210 If the shared top-level `#[display("...", args...)]` attribute contains no `{_variant}` placeholders,
211 then it acts as the default one for the variants without its own format.
212 ```rust
213 # use derive_more::Display;
214 #
215 #[derive(Display)]
216 #[display("Variant: {_0} & {}", _0)] // fields can be used too!
217 enum Enum {
218 #[display("A {_0}")]
219 A(i32),
220 B(u32),
221 #[display("c")]
222 C,
223 }
224
225 assert_eq!(Enum::A(1).to_string(), "A 1");
226 assert_eq!(Enum::B(2).to_string(), "Variant: 2 & 2");
227 assert_eq!(Enum::C.to_string(), "c");
228 ```
229
230
231 ### The `rename_all` attribute
232
233 When no format is specified, deriving `Display` uses the variant name verbatim as its format.
234 To control this the `#[display(rename_all = "...")]` attribute can be placed on structs, enums and variants.
235
236 The available casings are:
237 - `lowercase`
238 - `UPPERCASE`
239 - `PascalCase`
240 - `camelCase`
241 - `snake_case`
242 - `SCREAMING_SNAKE_CASE`
243 - `kebab-case`
244 - `SCREAMING-KEBAB-CASE`
245
246 ```rust
247 # use derive_more::Display;
248 #
249 #[derive(Display)]
250 #[display(rename_all = "lowercase")]
251 enum Enum {
252 VariantOne,
253 #[display(rename_all = "kebab-case")] // overrides the top-level one
254 VariantTwo
255 }
256
257 assert_eq!(Enum::VariantOne.to_string(), "variantone");
258 assert_eq!(Enum::VariantTwo.to_string(), "variant-two");
259 ```
260
261
262
263
264 ## Example usage
265
266 ```rust
267 # use std::path::PathBuf;
268 #
269 # use derive_more::{Display, Octal, UpperHex};
270 #
271 #[derive(Display)]
272 struct MyInt(i32);
273
274 #[derive(Display)]
275 #[display("({x}, {y})")]
276 struct Point2D {
277 x: i32,
278 y: i32,
279 }
280
281 #[derive(Display)]
282 #[display("Enum E: {_variant}")]
283 enum E {
284 Uint(u32),
285 #[display("I am B {:b}", i)]
286 Binary {
287 i: i8,
288 },
289 #[display("I am C {}", _0.display())]
290 Path(PathBuf),
291 }
292
293 #[derive(Display)]
294 #[display("Enum E2: {_0:?}")]
295 enum E2 {
296 Uint(u32),
297 String(&'static str, &'static str),
298 }
299
300 #[derive(Display)]
301 #[display("Hello there!")]
302 union U {
303 i: u32,
304 }
305
306 #[derive(Octal)]
307 #[octal("7")]
308 struct S;
309
310 #[derive(UpperHex)]
311 #[upper_hex("UpperHex")]
312 struct UH;
313
314 #[derive(Display)]
315 struct Unit;
316
317 #[derive(Display)]
318 struct UnitStruct {}
319
320 #[derive(Display)]
321 #[display("{}", self.sign())]
322 struct PositiveOrNegative {
323 x: i32,
324 }
325
326 impl PositiveOrNegative {
327 fn sign(&self) -> &str {
328 if self.x >= 0 {
329 "Positive"
330 } else {
331 "Negative"
332 }
333 }
334 }
335
336 assert_eq!(MyInt(-2).to_string(), "-2");
337 assert_eq!(Point2D { x: 3, y: 4 }.to_string(), "(3, 4)");
338 assert_eq!(E::Uint(2).to_string(), "Enum E: 2");
339 assert_eq!(E::Binary { i: -2 }.to_string(), "Enum E: I am B 11111110");
340 assert_eq!(E::Path("abc".into()).to_string(), "Enum E: I am C abc");
341 assert_eq!(E2::Uint(2).to_string(), "Enum E2: 2");
342 assert_eq!(E2::String("shown", "ignored").to_string(), "Enum E2: \"shown\"");
343 assert_eq!(U { i: 2 }.to_string(), "Hello there!");
344 assert_eq!(format!("{:o}", S), "7");
345 assert_eq!(format!("{:X}", UH), "UpperHex");
346 assert_eq!(Unit.to_string(), "Unit");
347 assert_eq!(UnitStruct {}.to_string(), "UnitStruct");
348 assert_eq!(PositiveOrNegative { x: 1 }.to_string(), "Positive");
349 assert_eq!(PositiveOrNegative { x: -1 }.to_string(), "Negative");
350 ```
351
352
353
354
355 [`format_args!()`]: https://doc.rust-lang.org/stable/std/macro.format_args.html
356
357 [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#formatting-parameters