The Default Trait
Default trait produces a default value for a type.
1. ```
#[derive(Debug, Default)]
```
2. ```
struct Derived {
```
3. ```
x: u32,
```
4. ```
y: String,
```
5. ```
z: Implemented,
```
6. ```
}
```
8. ```
#[derive(Debug)]
```
9. ```
struct Implemented(String);
```
11. ```
impl Default for Implemented {
```
12. ```
fn default() -> Self {
```
13. ```
Self("John Smith".into())
```
14. ```
}
```
15. ```
}
```
17. ```
fn main() {
```
18. ```
let default_struct = Derived::default();
```
19. ```
println!("{default_struct:#?}");
```
21. ```
let almost_default_struct =
```
22. ```
Derived { y: "Y is set!".into(), ..Derived::default() };
```
23. ```
println!("{almost_default_struct:#?}");
```
25. ```
let nothing: Option<Derived> = None;
```
26. ```
println!("{:#?}", nothing.unwrap_or_default());
```
27. ```
}
```
This slide should take about 5 minutes.
- It can be implemented directly or it can be derived via
#[derive(Default)]. - A derived implementation will produce a value where all fields are set to their default values.
- This means all types in the struct must implement
Defaulttoo. - Standard Rust types often implement
Defaultwith reasonable values (e.g.0,"", etc). - The partial struct initialization works nicely with default.
- The Rust standard library is aware that types can implement
Defaultand provides convenience methods that use it. - The
..syntax is called struct update syntax.
