Sub topic 14
Default: a standard initial value
This chapter assumes you can write structs and enums, implement a trait with impl Trait for Type, and read Option and Result. It covers how Default is defined, how to implement it by hand, where the standard library calls it, and which mistakes to avoid. The next chapters cover deriving Default, the #[default] attribute on enums, and the ..Default::default() struct update syntax in detail.
What the trait promises
Default is a trait with one function and no arguments:
pub trait Default: Sized {
fn default() -> Self;
}The function builds a value of the implementing type from nothing. The trait does not say what the value means. For a number it is zero, and for a collection it is empty. For your own types, it is whatever starting state you decide is reasonable.
The Sized bound means unsized types such as str or [T] cannot implement Default. You get String and Vec<T> instead.
Defaults in the standard library
Most standard types already implement Default.
| Type | Default value |
|---|---|
| Integers such as `i32`, `u8` | `0` |
| `f32`, `f64` | `0.0` |
| `bool` | `false` |
| `char` | `'\0'` |
| `String`, `&str` | empty string |
| `Vec<T>`, `HashMap<K, V>` | empty collection |
| `Option<T>` | `None` |
| `()` | `()` |
| Tuples and arrays of `Default` types | each element's default |
Option<T> is None for any T. It does not require T: Default.
Implementing Default by hand
Write the implementation yourself when the starting state is not "all zeros and empties".
#[derive(Debug)]
struct Config {
name: String,
retries: u32,
timeout_secs: f64,
}
impl Default for Config {
fn default() -> Self {
Config {
name: String::from("app"),
retries: 3,
timeout_secs: 30.0,
}
}
}
fn main() {
let a = Config::default();
let b: Config = Default::default();
let n: i32 = Default::default();
println!("{:?}", a);
println!("{:?}", b);
println!("{}", n);
}There are two ways to call it. Config::default() names the type. Default::default() has no type name, so the compiler infers it from the annotation on the left. This is why let n: i32 = Default::default(); works.
Where the standard library calls Default
You often use Default without writing the word. Several standard methods call it for you.
use std::collections::HashMap;
fn main() {
let text = "a b a c b a";
let mut counts: HashMap<&str, u32> = HashMap::new();
for w in text.split_whitespace() {
*counts.entry(w).or_default() += 1;
}
let mut pairs: Vec<_> = counts.into_iter().collect();
pairs.sort();
println!("{:?}", pairs);
let missing: Option<u32> = None;
println!("{}", missing.unwrap_or_default());
let mut buffer = vec![1, 2, 3];
let old = std::mem::take(&mut buffer);
println!("{:?} {:?}", old, buffer);
}The output is:
[("a", 3), ("b", 2), ("c", 1)]
0
[1, 2, 3] []Each call uses Default like this:
entry(key).or_default()insertsV::default()when the key is absent, then returns a mutable reference. HereVisu32, so the counter starts at0.unwrap_or_default()returns the contained value, orT::default()forNoneorErr.std::mem::take(&mut x)moves the value out and leavesT::default()in its place. This is how you take ownership of a field behind a&mutreference without leaving it invalid.
Because these methods need Default, implementing it on your own types makes them work with or_default() and mem::take too.
Using Default as a bound
Generic code can require T: Default to create a placeholder value without knowing the concrete type.
fn pad_to<T: Default + Clone>(mut v: Vec<T>, len: usize) -> Vec<T> {
v.resize(len, T::default());
v
}
fn main() {
println!("{:?}", pad_to(vec![1, 2], 4));
println!("{:?}", pad_to(vec![String::from("x")], 3));
}This prints [1, 2, 0, 0] and then ["x", "", ""]. Clone is also required because resize copies the filler value into each new slot.
Deciding whether a type should be Default
Derive Default when every field's default is acceptable. This is the typical case for settings structs. The next chapter covers it.
Write the implementation by hand when a field needs a non-zero starting value, such as a port 8080 or a host "localhost".
Do not implement it when no default makes sense. A UserId that must refer to a real account, or a type wrapping an open file, should not have a default. A fake default hides a bug that the compiler could have caught.
Common errors
A field without a Default blocks the derive. #[derive(Default)] requires every field's type to implement Default. If one field does not, the compiler reports the trait bound ... Default is not satisfied. Either implement Default for that field's type or write the outer impl by hand.
Default is not the same as new(). Nothing forces Type::new() and Type::default() to agree. If you provide both, make one call the other. Clippy's new_without_default lint warns when a public new() takes no arguments and Default is missing.
A zero default can be a valid but wrong value. A u32 timeout of 0 may mean "no wait" or "wait forever" depending on your code. If zero would be surprising, write the impl by hand.
Default values are not shared. Each call to default() returns a fresh, owned value. Two defaults of Vec<i32> are independent vectors, not references to one.
Exercise
A Counter struct has one field, hits: u32. You write let c = Default::default(); and then call c.hits. The compiler rejects it. What are two ways to fix the line, assuming Counter implements Default?
Show answer
The compiler cannot tell which type Default::default() should build. Fix it with an annotation, let c: Counter = Default::default();, or by naming the type, let c = Counter::default();.
Exercise
You collect words into a HashMap<String, Vec<String>> that maps a first letter to the words starting with it. Which method call lets you push a word into the list for a letter without first checking whether the key exists, and which trait makes it work?
Show answer
Use map.entry(letter).or_default().push(word);. It works because Vec<String> implements Default, so or_default() inserts an empty vector when the key is missing and returns a mutable reference to it.
Exercise
Why does Option<T> implement Default even when T does not?
Show answer
The default of Option<T> is None, which holds no T, so the standard library does not need T::default() to build it.