In Rust, why is `base` still usable after `Thermostat { room: String::from("office"), ..base }` but not after `Thermostat { target: 23.0, ..base }`?
answer
- which fields come from base
- moves or copies the rest
- String is not Copy
- partially moved value
- same struct type after ..
basics
~20 sStruct update syntax moves or copies every unlisted field from the base. Taking only Copy fields such as f64 leaves base whole; taking a String field moves it out, so base is partially moved and using it whole is E0382.
solid answer
~40 s`..base` fills each field you did not list explicitly from `base`, and the Reference says it **moves or copies** those fields. In the first expression `room` is given a fresh `String`, so only `target` and `current`, both `f64` and therefore `Copy`, come from `base`; nothing moves and `base` stays fully usable. In the second, `room` is not listed, so the `String` moves out of `base`. `base` is now **partially moved**: printing it or passing it whole fails with E0382, "borrow of partially moved value: `base`", while its remaining `Copy` fields can still be read one by one. Fixes are to supply the field (`room: base.room.clone()`) or clone the base (`..base.clone()`).
code
rust · 20 lines#[derive(Debug)]
struct Thermostat {
room: String,
target: f64,
current: f64,
}
fn main() {
let room = String::from("lab");
let base = Thermostat { room, target: 20.0, current: 18.5 }; // field init shorthand
// Only Copy fields are taken from `base`, so `base` stays whole.
let office = Thermostat { room: String::from("office"), target: 22.0, ..base };
println!("{base:?}\n{} at {}", office.room, office.target);
// `room` (a String) is taken from `base`: it is moved out of `base`.
let lab_warm = Thermostat { target: 23.0, ..base };
println!("{} {}", base.target, base.current); // the Copy fields are still readable
println!("{lab_warm:?}");
}go deeper
Know that ..base fills in the fields you did not write, and that a String field taken from base moves out of it.
Explain moves or copies field by field, the same-type rule, and why reading a Copy field of a partially moved base still compiles while using base whole is E0382.
Diagnose partial-move errors from the field the message names, and choose between supplying the field, cloning one field and cloning the base by cost.
Recognise struct update as a readability tool whose hidden moves surprise reviewers, and favour explicit fields where a value must remain usable.
## What struct update syntax does A **struct expression** builds a value by naming its fields: `Thermostat { room, target: 20.0, current: 18.5 }`. It may end with `..` followed by another expression, the **base**. The Reference calls this *functional update syntax* and states two rules: - The base must have **the same struct type** as the struct being built. `B { x: 2, ..a }` where `a: A` fails with E0308, mismatched types, even if `A` has the same field names; so does `..&base`, because a reference is not the struct type. - The new value uses the fields you wrote and **moves or copies the remaining fields** from the base. So `..base` is not a borrow and not a clone. It is a set of field-by-field moves, and each field follows its own type's rules: a `Copy` field is copied, anything else is moved. ## Walking through both expressions With `struct Thermostat { room: String, target: f64, current: f64 }`: 1. `Thermostat { room: String::from("office"), ..base }` takes `target` and `current` from `base`. Both are `f64`, which is `Copy`, so they are copied. Nothing is moved, so `base` remains a complete value you can print, pass or reuse. 2. `Thermostat { target: 23.0, ..base }` takes `room` and `current`. `current` is copied, but `room` is a `String`, so it moves into the new value. After the second expression `base` is **partially moved**. The compiler tracks moves per field, so: - reading `base.target` or `base.current` still compiles, because those fields were never moved; - `println!("{:?}", base)`, `base.clone()` or passing `base` to a function needs the whole struct and fails with **E0382**, "borrow of partially moved value: `base`", with a note that the partial move occurs because `base.room` has type `String`; - `&base.room` fails with E0382, "borrow of moved value: `base.room`". How partial moves work in general is covered with moves; what this leaf adds is that `..base` is a common place to cause one without writing any field access. ## Ways to keep the base | Goal | Write | Cost | |---|---|---| | keep `base` whole | give every non-`Copy` field explicitly | you supply a value for each | | copy one owned field | `room: base.room.clone(), ..base` | one `String` allocation | | copy everything | `..base.clone()` | needs `Clone`; clones every field | | give `base` away | leave it as is and stop using `base` | none | The base can be any expression of the right type, including a function call. A common idiom is `..Default::default()` for types that implement `Default`, which is covered with that trait. The base does not have to be a variable you keep. ## Two related rules - **Only unnamed fields are touched.** The Reference's own example builds `Point3d { y: 0, z: 10, .. base }` while `&mut base.y` is borrowed, and it compiles: only `base.x` is read. - **Field init shorthand.** When a local has the same name as a field, `Thermostat { room, .. }` means `room: room`. It moves the local `room` into the struct just as the long form would. Two limits come from neighbouring rules and get one line each here: every field must be visible where the expression is written, which is covered with visibility; and if the struct implements `Drop`, moving a field out through `..base` is E0509, which is covered with `Drop`. ## Where struct update earns its place - **Variants of one value.** Test fixtures and configuration presets often differ from a base in one or two fields; `Thermostat { target: 23.0, ..base_fixture() }` says exactly what differs. - **A fresh base each time.** When the base is a function call rather than a variable, nothing you keep is moved, so partial moves cannot surprise you. - **Readability limit.** When most fields are listed explicitly anyway, `..base` hides which few came from elsewhere; listing every field can be clearer. ## What interviewers want to hear - `..base` moves or copies; it never borrows. - Whether `base` survives depends only on which fields were taken and whether they are `Copy`. - The error after a partial move names the field that moved, which tells you what to supply or clone.
- Does `..base` work if `base` is a different struct with the same fields?No. The base must have the same struct type as the value being built, so `B { x: 2, ..a }` with `a: A` is E0308, mismatched types. A reference does not qualify either: `..&base` is E0308 too, because `&Thermostat` is not `Thermostat`.
- After `let b = Thermostat { target: 23.0, ..base };`, can you assign `base.room = String::new()` and use `base` again?Yes, if `base` is declared `let mut`. Assigning a new value to the moved field makes `base` whole again, so it can then be printed or passed. Without `mut` the assignment itself is rejected with E0594, "cannot assign to `base.room`, as `base` is not declared as mutable".
- Why prefer `room: base.room.clone()` over `..base.clone()`?`..base.clone()` clones every field, including ones you then overwrite, and requires `Clone` on the type. Cloning just the one field that would move costs one allocation and works whether or not the struct is `Clone`.
- ..base borrows the base, so it is always usable afterwards
- ..base clones the base's fields
- The base can be any struct that has the missing field names
- After a partial move none of base's fields can be read
- Field init shorthand copies the local instead of moving it