Debian Codegraph @

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

raw
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
17
18
19
20 ## The format of the format
21
22 You supply a format by attaching an attribute of the syntax: `#[display("...", args...)]`.
23 The format supplied is passed verbatim to `write!`. The arguments supplied handled specially,
24 due to constraints in the syntax of attributes. In the case of an argument being a simple
25 identifier, it is passed verbatim. If an argument is a string, it is **parsed as an expression**,
26 and then passed to `write!`.
27
28 The variables available in the arguments is `self` and each member of the variant,
29 with members of tuple structs being named with a leading underscore and their index,
30 i.e. `_0`, `_1`, `_2`, etc.
31
32
33 ### Other formatting traits
34
35 The syntax does not change, but the name of the attribute is the snake case version of the trait.
36 E.g. `Octal` -> `octal`, `Pointer` -> `pointer`, `UpperHex` -> `upper_hex`.
37
38 Note, that `Debug` has a slightly different API and semantics, described in its docs, and so,
39 requires a separate `debug` feature.
40
41
42 ### Generic data types
43
44 When deriving `Display` (or other formatting trait) for a generic struct/enum, all generic type
45 arguments used during formatting are bound by respective formatting trait.
46
47 E.g., for a structure `Foo` defined like this:
48 ```rust
49 # use derive_more::Display;
50 #
51 # trait Trait { type Type; }
52 #
53 #[derive(Display)]
54 #[display("{} {} {:?} {:p}", a, b, c, d)]
55 struct Foo<'a, T1, T2: Trait, T3> {
56 a: T1,
57 b: <T2 as Trait>::Type,
58 c: Vec<T3>,
59 d: &'a T1,
60 }
61 ```
62
63 The following where clauses would be generated:
64 * `T1: Display + Pointer`
65 * `<T2 as Trait>::Type: Debug`
66 * `Bar<T3>: Display`
67
68
69 ### Custom trait bounds
70
71 Sometimes you may want to specify additional trait bounds on your generic type parameters, so that they
72 could be used during formatting. This can be done with a `#[display(bound(...))]` attribute.
73
74 `#[display(bound(...))]` accepts code tokens in a format similar to the format
75 used in angle bracket list (or `where` clause predicates): `T: MyTrait, U: Trait1 + Trait2`.
76
77 Only type parameters defined on a struct allowed to appear in bound-string and they can only be bound
78 by traits, i.e. no lifetime parameters or lifetime bounds allowed in bound-string.
79
80 `#[display("fmt", ...)]` arguments are parsed as an arbitrary Rust expression and passed to generated
81 `write!` as-is, it's impossible to meaningfully infer any kind of trait bounds for generic type parameters
82 used this way. That means that you'll **have to** explicitly specify all trait bound used. Either in the
83 struct/enum definition, or via `#[display(bound(...))]` attribute.
84
85 Note how we have to bound `U` and `V` by `Display` in the following example, as no bound is inferred.
86 Not even `Display`.
87
88 ```rust
89 # use derive_more::Display;
90 #
91 # trait MyTrait { fn my_function(&self) -> i32; }
92 #
93 #[derive(Display)]
94 #[display(bound(T: MyTrait, U: Display))]
95 #[display("{} {} {}", a.my_function(), b.to_string().len(), c)]
96 struct MyStruct<T, U, V> {
97 a: T,
98 b: U,
99 c: V,
100 }
101 ```
102
103
104
105
106 ## Example usage
107
108 ```rust
109 # use std::path::PathBuf;
110 #
111 # use derive_more::{Display, Octal, UpperHex};
112 #
113 #[derive(Display)]
114 struct MyInt(i32);
115
116 #[derive(Display)]
117 #[display("({x}, {y})")]
118 struct Point2D {
119 x: i32,
120 y: i32,
121 }
122
123 #[derive(Display)]
124 enum E {
125 Uint(u32),
126 #[display("I am B {:b}", i)]
127 Binary {
128 i: i8,
129 },
130 #[display("I am C {}", _0.display())]
131 Path(PathBuf),
132 }
133
134 #[derive(Display)]
135 #[display("Hello there!")]
136 union U {
137 i: u32,
138 }
139
140 #[derive(Octal)]
141 #[octal("7")]
142 struct S;
143
144 #[derive(UpperHex)]
145 #[upper_hex("UpperHex")]
146 struct UH;
147
148 #[derive(Display)]
149 struct Unit;
150
151 #[derive(Display)]
152 struct UnitStruct {}
153
154 #[derive(Display)]
155 #[display("{}", self.sign())]
156 struct PositiveOrNegative {
157 x: i32,
158 }
159
160 impl PositiveOrNegative {
161 fn sign(&self) -> &str {
162 if self.x >= 0 {
163 "Positive"
164 } else {
165 "Negative"
166 }
167 }
168 }
169
170 assert_eq!(MyInt(-2).to_string(), "-2");
171 assert_eq!(Point2D { x: 3, y: 4 }.to_string(), "(3, 4)");
172 assert_eq!(E::Uint(2).to_string(), "2");
173 assert_eq!(E::Binary { i: -2 }.to_string(), "I am B 11111110");
174 assert_eq!(E::Path("abc".into()).to_string(), "I am C abc");
175 assert_eq!(U { i: 2 }.to_string(), "Hello there!");
176 assert_eq!(format!("{:o}", S), "7");
177 assert_eq!(format!("{:X}", UH), "UpperHex");
178 assert_eq!(Unit.to_string(), "Unit");
179 assert_eq!(UnitStruct {}.to_string(), "UnitStruct");
180 assert_eq!(PositiveOrNegative { x: 1 }.to_string(), "Positive");
181 assert_eq!(PositiveOrNegative { x: -1 }.to_string(), "Negative");
182 ```