Sub topic 15
Deriving Default and #[default] for enums
This chapter assumes you know how #[derive(...)] works and what the Default trait is: a default() function that returns a standard initial value for a type. It also assumes you can read basic structs and enums.
Deriving Default on a struct
When every field has a sensible default, you can ask the compiler to write the implementation:
#[derive(Debug, Default)]
struct Settings {
name: String,
retries: u32,
verbose: bool,
tag: Option<String>,
}
fn main() {
let s = Settings::default();
println!("{:?}", s);
}This prints Settings { name: "", retries: 0, verbose: false, tag: None }. The derived code calls Default::default() on each field and builds the struct from the results.
| Type | Default value |
|---|---|
| Integers and floats | `0` and `0.0` |
| `bool` | `false` |
| `char` | `'\0'` |
| `String`, `Vec<T>` | empty |
| `Option<T>` | `None` |
| Tuples and arrays | the default of each element |
Deriving Default on an enum
An enum has no natural "first field", so the compiler needs you to pick a variant. Mark it with #[default]:
#[derive(Debug, Default)]
enum Mode {
#[default]
Normal,
Fast,
}
#[derive(Debug, Default)]
struct Job {
id: u32,
mode: Mode,
}
fn main() {
println!("{:?}", Job::default());
println!("{:?}", Mode::Fast);
}Job::default() gives Job { id: 0, mode: Normal }. Because Mode now implements Default, Job can derive it too.
Common errors
- A field type has no
Default. Deriving on a struct fails if any field's type does not implementDefault. Either implementDefaultfor that type or write the struct's implementation by hand. - No
#[default]on an enum.#[derive(Default)]on an enum without the attribute is a compile error. - More than one
#[default]. Only one variant can carry it. #[default]on a variant with data. The attribute works only on unit variants, such asNormal. A variant likeCustom(u8)is rejected. Writeimpl Defaultby hand if you need that.- Generics. For
struct Wrapper<T>, the derive adds the boundT: Default. The derived implementation exists only whenTimplementsDefault.
Choosing derive or manual
Derive when every field's default is acceptable. Write impl Default by hand when any field needs a specific value, such as port: 8080 or host: "localhost". You can also mix the two. Derive Default on small types like Mode, and call Mode::default() inside a hand-written implementation for the larger type.
Exercise
This code does not compile. Give two different fixes. enum Level { Low, High } #[derive(Default)] struct Config { level: Level }
Show answer
The derive on Config needs Level: Default, and Level does not implement it. Fix 1: add #[derive(Default)] to Level and mark one variant, for example #[default] Low. Fix 2: write impl Default for Level { fn default() -> Self { Level::Low } } by hand. Either way, Config can then keep its derive.