Sub topic 14
Default: a standard initial value
This chapter assumes you can write impl Trait for Type and use println! with {:?}. It also assumes you know basic structs and Option.
What Default promises
Default is a standard trait with one method: fn default() -> Self. The method takes no arguments and returns a value of the implementing type. The trait promises that the type has one agreed "starting" value.
Many standard types already implement it:
| Type | `Default::default()` |
|---|---|
| `i32`, `u16`, and other integers | `0` |
| `f64` | `0.0` |
| `bool` | `false` |
| `char` | `'\0'` |
| `String` | `""` |
| `Vec<T>` | empty vector |
| `Option<T>` | `None` |
| Tuples of default types | a tuple of each default |
Implementing it by hand
Write the implementation yourself when the starting value is not simply "zero for everything". A server with port 0 and an empty host is not useful, so this one sets real values.
#[derive(Debug)]
struct Server {
host: String,
port: u16,
}
impl Default for Server {
fn default() -> Self {
Server {
host: "localhost".to_string(),
port: 8080,
}
}
}
fn main() {
let a = Server::default();
let b: Server = Default::default();
println!("{:?}", a);
println!("{:?}", b);
let n: i32 = Default::default();
let s = String::default();
let v: Vec<u8> = Vec::default();
println!("{} {:?} {:?}", n, s, v);
}The program prints two identical Server values. It then prints 0 "" [].
Server::default() and Default::default() do the same thing here. The second form works only when the compiler can infer the type, which is why b and n carry type annotations.
How it is called
default has no self parameter, so you call it on a type, not on a value. Because the return type is Self, type inference does most of the work.
flowchart LRThe diagram below shows how a call finds its implementation.
Where the standard library uses it
Several standard methods rely on Default, so your own types work with them once they implement it.
fn main() {
let port: u16 = "not a number".parse().unwrap_or_default();
println!("{}", port);
let name: Option<String> = None;
println!("{:?}", name.unwrap_or_default());
}This prints 0 and then an empty string (""). unwrap_or_default returns the success value, or T::default() when the result is an error or None. Other helpers, such as mem::take and HashMap::entry(..).or_default(), also require Default.
The next chapter covers deriving Default so you don't have to write it for simple types.
Exercise
What does let x: (i32, bool, String) = Default::default(); produce, and why does the line need the type annotation?
Show answer
It produces (0, false, ""), because each element uses its own type's default. The annotation is needed because Default::default() has no arguments, so the compiler can learn which implementation to call only from the expected type.