Sub topic 16
Overriding some fields with ..Default::default()
This chapter assumes you know how to derive or implement Default, how struct literals work, and the basics of moves and Copy types. Here you will learn the struct update syntax, how it combines with Default, and the ownership and visibility rules that cause surprises.
The syntax
A struct literal can end with .. followed by an expression. Every field you did not list is taken from that expression. The expression must have the same type as the struct you are building.
With Default, this lets you set the fields you care about and leave the rest at their standard values.
#[derive(Debug, Default)]
enum Mode {
#[default]
Normal,
Fast,
}
#[derive(Debug)]
struct Server {
host: String,
port: u16,
mode: Mode,
}
impl Default for Server {
fn default() -> Self {
Server {
host: "localhost".to_string(),
port: 8080,
mode: Mode::default(),
}
}
}
fn main() {
let a = Server {
port: 9000,
..Default::default()
};
let b = Server {
mode: Mode::Fast,
host: "example.org".to_string(),
..Default::default()
};
println!("{:?}", a);
println!("{:?}", b);
}Three rules apply:
..exprmust come last in the literal. You cannot write a trailing comma after it.- The order of the listed fields does not matter.
- The compiler infers the type of
Default::default()from the struct being built. You do not need to writeServer::default(), though that form is also valid.
What the compiler does
The base expression is evaluated once, and the result is a complete value of the struct type. The compiler then moves or copies each unlisted field out of that value into the new struct.
The diagram shows the flow.
One consequence is cost. ..Default::default() builds every field of the default value, including the fields you override. If a default field allocates memory or does other expensive work, that work still happens, and the unused value is dropped.
Any value can be the base
Default::default() is only one option. The base can be a variable, a function call, or a field access, as long as it has the right type. This matters for ownership.
#[derive(Debug, Clone)]
struct Config {
name: String,
retries: u32,
verbose: bool,
}
fn main() {
let base = Config {
name: "base".to_string(),
retries: 3,
verbose: false,
};
// Clone first, so base is untouched.
let a = Config {
retries: 5,
..base.clone()
};
// name is listed, so only Copy fields are taken from base.
let b = Config {
name: "b".to_string(),
..base
};
println!("{:?}", base); // still fully usable
// name is not listed, so the String is moved out of base.
let c = Config {
retries: 1,
..base
};
println!("{:?} {:?} {:?}", a, b, c);
// base.name is moved, but a Copy field is still readable.
println!("{}", base.retries);
// println!("{:?}", base); // error: borrow of partially moved value
}The rule is simple. The syntax moves each unlisted field that is not Copy, and copies each field that is. Moving a field leaves the original variable partially moved. You can still use its other fields, but not the whole value.
With ..Default::default() this never bites you, because the base is a temporary that nothing else refers to.
Gotchas
Private fields
The syntax reads every unlisted field, so every unlisted field must be visible at the call site. If the struct has a private field and you build it from another module, the code does not compile, even when the field has a default.
The usual fix is to give the type a constructor or method inside its own module.
mod limits {
#[derive(Debug, Default)]
pub struct Limits {
pub max: u32,
secret: u32,
}
impl Limits {
pub fn with_max(max: u32) -> Self {
Limits {
max,
..Default::default()
}
}
}
}
fn main() {
let l = limits::Limits::with_max(10);
println!("{:?}", l);
// limits::Limits { max: 10, ..Default::default() } would not compile:
// the field `secret` is private.
}Inside the limits module the syntax works, because secret is visible there.
Structs only
Struct update syntax works on structs with named fields, and on tuple structs using the index form such as Pair { 0: 5, ..base }. It does not work on enums. Enum variants are built by naming the variant, and an enum value has no "remaining fields" to fill in.
Changing the defaults later
When you add a field to a struct that derives Default, every ..Default::default() literal picks up the new field automatically. That is usually what you want. It also means a literal that spells out every field will fail to compile after the change, so callers that use the syntax are easier to maintain.
If you change an existing default value, callers that relied on it silently get the new value. Treat changing a default as a behavior change.
Comparing approaches
| Approach | Good for | Weakness |
|---|---|---|
| Full struct literal | Small structs where every value matters | Breaks when a field is added |
| `..Default::default()` | A few overrides on a struct with sensible defaults | Needs `Default`, needs visible fields |
| `..existing_value` | Making a variant of a value you already have | Moves non-`Copy` fields |
| Builder methods | Validation, private fields, many optional values | More code to write |
Choosing the syntax
Use ..Default::default() when the type has one obvious default and callers typically change two or three fields. Test configurations are a good fit, because each test states only the field it cares about.
Avoid it when a "default" value would be misleading or unsafe. A Credentials type with an empty password should not implement Default just to enable this syntax. Make the caller list every field, or provide a constructor that takes the required values.
Exercises
Exercise
A struct Settings has fields name: String, retries: u32, and verbose: bool, and it derives Default. Write an expression that creates a Settings with retries set to 5 and the other fields at their defaults.
Show answer
Settings { retries: 5, ..Default::default() } builds the value. The derived default gives an empty String for name and false for verbose, and the literal overrides only retries.
Exercise
You write let b = Config { retries: 1, ..base }; where Config has a String field name that you did not list, and base is a named variable. Afterwards println!("{:?}", base) fails to compile. Why, and how do you keep base usable?
Show answer
The unlisted name field is a String, so it is moved out of base. That leaves base partially moved, and Debug needs the whole value. Either list name explicitly so only Copy fields are taken, or write ..base.clone() so the original is never touched.
Exercise
You add a private field to a struct in module a. Code in module b that uses ..Default::default() on that struct stops compiling. Why, and what is a fix?
Show answer
The syntax reads every unlisted field, and a private field is not visible from module b. Add a constructor or builder method inside module a that uses ..Default::default(), and call it from module b.