Sub topic 4
Building from another instance with struct update syntax
This chapter assumes you can define a struct, create an instance with named fields, and follow Rust's move and borrow rules. You should also know what Clone and Default do at a basic level. The topic is the .. syntax, which fills in the remaining fields of a new struct from another value. It looks like a copy, but it moves or copies each field separately, and that affects whether the original value is still usable.
The basic form
Struct update syntax goes at the end of a struct literal. You list the fields you want to set, then write .. followed by an expression. Every field you did not list is taken from that expression.
#[derive(Debug, Clone, Default)]
struct Config {
name: String,
retries: u32,
verbose: bool,
}
fn main() {
let base = Config {
name: String::from("base"),
..Default::default()
};
let custom = Config {
retries: 5,
..base.clone()
};
println!("{:?}", base);
println!("{:?}", custom);
}This prints:
Config { name: "base", retries: 0, verbose: false }
Config { name: "base", retries: 5, verbose: false }In the first literal, ..Default::default() supplies retries and verbose. The compiler infers that Default::default() must produce a Config, because the expression after .. must have the same type as the struct being built. In the second literal, ..base.clone() supplies name and verbose.
Rules for the base expression
- It must come last in the literal. You cannot put fields after it, and you cannot write a trailing comma after it.
- It must have exactly the same type as the struct being built. Rust does not accept a base of a different generic instantiation, even if the field types you override would make it fit.
- It can be any expression, not only a variable. Function calls,
Default::default(), and.clone()results all work. - It is evaluated after the explicit field expressions, which run in the order you wrote them.
What actually happens to each field
Struct update syntax is shorthand. The compiler treats each field you did not list as if you had written field: base.field. Each of those is an ordinary field access, so the usual ownership rules apply field by field:
- A field whose type implements
Copyis copied. The source keeps its value. - A field whose type does not implement
Copy, such asStringorVec<T>, is moved out of the source.
The consequence is that ..base does not always consume base. What matters is which fields were taken and whether they were Copy.
#[derive(Debug, Clone)]
struct Config {
name: String,
retries: u32,
verbose: bool,
}
fn main() {
let a = Config {
name: String::from("a"),
retries: 1,
verbose: true,
};
// Only retries and verbose are taken from `a`. Both are Copy.
let b = Config {
name: String::from("b"),
..a
};
println!("{:?} {:?}", a, b); // `a` is still fully usable
// Now `name` is taken from `a`, and String is not Copy.
let c = Config { retries: 9, ..a };
println!("{} {}", a.retries, a.verbose); // still fine
println!("{:?}", c);
// println!("{}", a.name); // error: borrow of moved value: `a.name`
// println!("{:?}", a); // error: borrow of partially moved value: `a`
}The first update leaves a intact because the only fields it needed were Copy. The second update moves a.name into c. After that, a is partially moved. You can still read a.retries and a.verbose, but you cannot use a as a whole or read a.name.
The table summarizes the cases for a base variable.
| What the update takes from the base | Effect on the base variable |
|---|---|
| Only `Copy` fields | Base stays fully usable |
| At least one non-`Copy` field | Base is partially moved; the untouched fields stay usable |
| All non-`Copy` fields are overridden explicitly | Base stays fully usable |
Keeping the original: clone the base
If you want to keep using the base as a whole, pass a clone. The expression ..base.clone() creates a temporary full copy, and the update moves fields out of that temporary. The cost is that every field is cloned, including the ones you override, because clone runs before the update picks fields. For a struct with a large Vec, this can be wasteful. If you override the expensive field anyway, consider moving out of the base and accepting that it is partially moved.
A common use: defaults with overrides
The most frequent pattern pairs ..Default::default() with a struct that derives Default. You name only the fields that differ from the defaults:
#[derive(Debug, Default)]
struct Options {
timeout_secs: u32,
follow_redirects: bool,
user_agent: String,
}
fn main() {
let opts = Options {
timeout_secs: 30,
..Default::default()
};
println!("{:?}", opts);
}This prints Options { timeout_secs: 30, follow_redirects: false, user_agent: "" }. The default for each field comes from that field's own Default implementation: 0 for integers, false for bool, and an empty string for String. The base is a temporary here, so there is no partially moved variable to worry about.
Edge cases and errors
Private fields. Struct update syntax reads every field not listed, so all of them must be visible at the place you write the literal. If the struct has private fields and you are outside its module, the compiler rejects the literal with an error that a field is private, even if you never named that field. This is one reason library types with private fields use constructors or builders instead.
Types that implement Drop. A type with a Drop implementation cannot have non-Copy fields moved out of it. Using ..base that would move such a field fails with an error that you cannot move out of a type that implements Drop.
Tuple structs. Struct update syntax needs field names, so it works with named-field structs only. A tuple struct such as Meters(f64) has no equivalent.
Overriding everything. If you list every field, ..base is allowed but takes nothing from the base. Recent compilers warn about this, since the base expression is redundant.
Not a general clone. The syntax does not copy the struct bitwise or guarantee a shallow copy. It is the field-by-field move or copy described above, and the compiler checks it like any other field access.
Summary
..basegoes last and fills every unlisted field from an expression of the same struct type.- Each unlisted field is copied if it is
Copyand moved if it is not. - The base variable is partially moved only when a non-
Copyfield was taken from it. - Use
.clone()on the base to keep the original whole, at the cost of cloning every field. - All fields must be visible where you write the literal, and
Droptypes block moves out of them.
Exercise
Given struct User { name: String, age: u32 } and let u1 = User { name: String::from("Ana"), age: 30 };, you write let u2 = User { age: 31, ..u1 };. Can you then use u1.age? Can you use u1.name? Can you use u1 as a whole? Explain why.
Show answer
You can use u1.age, because it was not taken from u1 (it was overridden) and it is Copy anyway. You cannot use u1.name or u1 as a whole. The update took name from u1, and String is not Copy, so name was moved into u2 and u1 is partially moved. Writing User { age: 31, ..u1.clone() } instead would keep u1 fully usable.
Exercise
A module defines pub struct Settings { pub level: u8, secret: String } and derives Default. Code outside the module writes Settings { level: 3, ..Default::default() }. Does it compile? Why or why not?
Show answer
It does not compile. Struct update syntax reads the unlisted field secret from the base, and secret is private outside the module, so the compiler reports a private field error. The module should expose a constructor or builder, such as a Settings::with_level(level) function, instead.