Sub topic 15
Deriving Default and #[default] for enums
This chapter assumes you know how #[derive(...)] works, what the Default trait is, and basic struct and enum syntax. It covers what #[derive(Default)] generates, how to pick the default variant of an enum, and where derive stops being the right tool.
What derive generates
Default has one method and no arguments:
pub trait Default: Sized {
fn default() -> Self;
}Writing #[derive(Default)] on a struct generates an impl that calls Default::default() on each field and builds the struct from the results. The derive works only if every field's type implements Default.
#[derive(Debug, Default)]
struct Settings {
name: String,
retries: u32,
verbose: bool,
ratio: f64,
tags: Vec<String>,
timeout: Option<u64>,
}
fn main() {
println!("{:#?}", Settings::default());
}The output shows an empty string, zeros, false, an empty vector, and None. These are the "empty" or "zero" values of each type:
| Type | Default value |
|---|---|
| Integers (`i32`, `u8`, `usize`, ...) | `0` |
| `f32`, `f64` | `0.0` |
| `bool` | `false` |
| `char` | `'\0'` |
| `String`, `&str` | the empty string |
| `Vec<T>`, `HashMap<K, V>`, `HashSet<T>` | an empty collection |
| `Option<T>` | `None` |
| `()` and tuples of `Default` types | each element's default |
Note that Option<T> defaults to None for any T. It does not require T: Default.
Deriving Default on an enum
A struct has one obvious shape, so derive can fill it in. An enum has several variants, and the compiler cannot guess which one you want. Since Rust 1.62 you mark the chosen variant with the #[default] attribute:
#[derive(Debug, Default, PartialEq)]
enum LogLevel {
Error,
Warn,
#[default]
Info,
Trace,
}
#[derive(Debug, Default)]
struct Config {
level: LogLevel,
name: String,
}
fn main() {
let c = Config::default();
println!("{:?}", c);
assert_eq!(LogLevel::default(), LogLevel::Info);
}Config derives Default because both of its fields do. The nested derive picks LogLevel::Info automatically, so the printed value is Config { level: Info, name: "" }.
Two rules apply to #[default]:
- Exactly one variant may carry it. Zero or two is a compile error.
- The variant must be a unit variant, meaning it has no fields. A variant like
Custom(u8)cannot be the default, because derive would have to invent a payload.
If the natural default of an enum carries data, write the impl yourself:
#[derive(Debug)]
enum Retry {
Never,
Times(u32),
}
impl Default for Retry {
fn default() -> Self {
Retry::Times(3)
}
}
fn main() {
println!("{:?}", Retry::default());
println!("{:?}", Retry::Never);
}Why derive can fail
Every field must implement Default. If one does not, the derive fails with an error that points at the field. This is common with types that have no meaningful empty state, such as a database connection or a file handle.
You have two choices when this happens:
- Give the field's type its own
Defaultimplementation, if an empty state makes sense. - Drop the derive and write
impl Default for YourTypeby hand, filling in each field explicitly.
Do not add Default to a type only to make a derive compile. A fake default such as a connection to a placeholder address can hide bugs, because the value looks valid.
The generic type parameter gotcha
For a generic type, derive adds a bound T: Default on every type parameter, whether or not the fields need it. This is stricter than necessary.
#[derive(Debug, Default)]
struct Slot<T> {
item: Option<T>,
}
fn main() {
let a: Slot<i32> = Slot::default();
println!("{:?}", a);
}This works because i32 implements Default. Now consider a type that does not:
#[allow(dead_code)]
struct Token(u8); // no Default
struct Slot<T> {
item: Option<T>,
}
impl<T> Default for Slot<T> {
fn default() -> Self {
Slot { item: None }
}
}
fn main() {
let b: Slot<Token> = Slot::default();
println!("{}", b.item.is_none());
}With #[derive(Default)], Slot<Token>::default() would be rejected, because the generated bound demands Token: Default. The manual impl<T> Default for Slot<T> has no such bound, so it accepts any T. This is a case where writing the impl by hand is strictly more flexible than derive.
Using defaults beyond the constructor
Default is a contract that other APIs rely on. Once your type implements it, these standard helpers work with it:
use std::collections::HashMap;
fn main() {
let mut counts: HashMap<String, u32> = HashMap::new();
for w in "a b a c a".split(' ') {
*counts.entry(w.to_string()).or_default() += 1;
}
let mut pairs: Vec<_> = counts.iter().collect();
pairs.sort();
println!("{:?}", pairs);
let missing: Option<String> = None;
println!("{:?}", missing.unwrap_or_default());
let mut buf = vec![1, 2, 3];
let old = std::mem::take(&mut buf);
println!("{:?} {:?}", old, buf);
}entry(...).or_default()insertsT::default()when the key is missing, then gives you a mutable reference.unwrap_or_default()returns the contained value orT::default().std::mem::takemoves a value out of a&mutreference and leavesT::default()behind. This is the usual way to move out of a field when you only hold&mut self.
Each of these needs T: Default, which is a practical reason to implement it on your own types.
Common errors and edge cases
- Missing
#[default]. Deriving on an enum without it fails to compile. Add the attribute to one unit variant. - Attribute on a data-carrying variant.
#[default]onCustom(u8)is rejected. Use a manual impl. - Field type without Default. The derive fails. Implement
Defaultfor that type or write the outer impl by hand. - A derived default that is not valid. A
u16port derives to0, which is not a usable port. Derive is correct only when the zero or empty value is a legal state. TheServertype in the next chapter section uses a manual impl for this reason. - Adding a field later. Derived defaults update automatically when you add a field. A manual impl will fail to compile until you add the new field, which is often what you want because it forces a decision.
Exercise
You write #[derive(Default)] enum Shape { Circle(f64), Square(f64) }. Why does it fail, and how do you fix it so that Shape::default() returns Circle(1.0)?
Show answer
Derive needs a variant marked #[default], and that variant must be a unit variant with no fields. Neither variant qualifies, so the derive cannot compile. Remove the derive and write the impl by hand: impl Default for Shape { fn default() -> Self { Shape::Circle(1.0) } }.
Exercise
A struct Cache<T> { items: Vec<T> } derives Default. Why does Cache::<Connection>::default() fail when Connection has no Default impl, and what change makes it compile?
Show answer
Derive adds the bound T: Default to the generated impl, even though Vec<T> is empty by default for any T. Replace the derive with impl<T> Default for Cache<T> { fn default() -> Self { Cache { items: Vec::new() } } }, which has no bound on T.