]> git.proxmox.com Git - rustc.git/blob - vendor/derivative/doc/Default.md
New upstream version 1.75.0+dfsg1
[rustc.git] / vendor / derivative / doc / Default.md
1 # Custom attributes
2 The `Default` trait supports the following attributes:
3
4 * **Container attributes**
5 * [`Default(bound="<where-clause or empty>")`](#custom-bound)
6 * [`Default="new"`](#new-function)
7 * **Variant attributes**
8 * [`Default`](#default-enumeration)
9 * **Field attributes**
10 * [`Default(bound="<where-clause or empty>")`](#custom-bound)
11 * [`Default(value="<expr>")`](#setting-the-value-of-a-field)
12
13 # Default enumeration
14
15 You can use *derivative* to derive a default implementation on enumerations!
16 This does not work with *rustc*'s `#[derive(Default)]`.
17 All you need is to specify what variant is the default value:
18
19 ```rust
20 # extern crate derivative;
21 # use derivative::Derivative;
22 #[derive(Debug, Derivative)]
23 #[derivative(Default)]
24 enum Enum {
25 A,
26 #[derivative(Default)]
27 B,
28 }
29
30 println!("{:?}", Enum::default()); // B
31 ```
32
33 # Setting the value of a field
34
35 You can use *derivative* to change the default value of a field in a `Default`
36 implementation:
37
38 ```rust
39 # extern crate derivative;
40 # use derivative::Derivative;
41 #[derive(Debug, Derivative)]
42 #[derivative(Default)]
43 struct Foo {
44 foo: u8,
45 #[derivative(Default(value="42"))]
46 bar: u8,
47 }
48
49 println!("{:?}", Foo::default()); // Foo { foo: 0, bar: 42 }
50 ```
51
52 # `new` function
53
54 You can use *derivative* to derive a convenience `new` method for your type
55 that calls `Default::default`:
56
57 ```rust
58 # extern crate derivative;
59 # use derivative::Derivative;
60 #[derive(Debug, Derivative)]
61 #[derivative(Default(new="true"))]
62 struct Foo {
63 foo: u8,
64 bar: u8,
65 }
66
67 println!("{:?}", Foo::new()); // Foo { foo: 0, bar: 0 }
68 ```
69
70 # Custom bound
71
72 The following does not work because `derive` adds a `T: Default` bound on the
73 `impl Default for Foo<T>`:
74
75 ```rust,compile_fail
76 # extern crate derivative;
77 # use derivative::Derivative;
78 #[derive(Default)]
79 struct Foo<T> {
80 foo: Option<T>,
81 }
82
83 struct NonDefault;
84
85 Foo::<NonDefault>::default(); // gives:
86 // error: no associated item named `default` found for type `Foo<NonDefault>` in the current scope
87 // = note: the method `default` exists but the following trait bounds were not satisfied: `NonDefault : std::default::Default`
88 ```
89
90 That bound however is useless as `Option<T>: Default` for any `T`.
91 `derivative` allows you to explicitly specify a bound if the inferred one is not
92 correct:
93
94 ```rust
95 # extern crate derivative;
96 # use derivative::Derivative;
97 #[derive(Derivative)]
98 #[derivative(Default(bound=""))] // don't need any bound
99 struct Foo<T> {
100 foo: Option<T>,
101 }
102
103 struct NonDefault;
104
105 Foo::<NonDefault>::default(); // works!
106 ```