skip to content

In Rust, after `let endpoint = cfg.endpoint;` moves one `String` field out of a `Config` struct, what can you still do with `cfg`?

level: middleimportance: should knowfreq 48%

answer

  1. moves tracked per field
  2. other fields stay initialised
  3. the whole value is off limits
  4. assign the field back
  5. Drop types forbid it: E0509

basics

~20 s

Rust tracks moves per field: cfg's other fields stay readable, borrowable and movable, but any use of cfg as a whole fails with E0382 until the moved field is reassigned. A struct that implements Drop forbids the partial move (E0509).

solid answer

~40 s

Moving `cfg.endpoint` is a **partial move**: rustc marks that one field as moved and leaves `cfg.tags` and `cfg.retries` initialised, so `cfg.tags.len()`, `&cfg.tags` or moving `cfg.tags` somewhere else all compile, and reading the `u32` `retries` just copies it. What fails is anything that needs the whole struct, such as passing `cfg` by value, `println!("{:?}", cfg)` or calling a `&self` method, with E0382 "borrow of partially moved value: `cfg`". If `cfg` is declared `let mut`, assigning a new `String` to `cfg.endpoint` makes it whole again. When `cfg` goes out of scope, only the fields still in it are dropped. If `Config` implements `Drop`, rustc rejects the move itself with E0509, because the destructor must see every field.

code

rust · 17 lines
rust
#[derive(Debug)]
struct Config {
    endpoint: String,
    tags: Vec<String>,
    retries: u32,
}

fn main() {
    let cfg = Config {
        endpoint: String::from("https://ingest.internal/v1"),
        tags: vec![String::from("edge")],
        retries: 3,
    };
    let endpoint = cfg.endpoint; // partial move: only this field leaves
    println!("{endpoint} {:?} {}", cfg.tags, cfg.retries); // other fields still usable
    println!("{:?}", cfg); // whole value: rejected
}

go deeper

for a junior

Know that moving one String field out of a struct leaves the other fields usable but the struct as a whole unusable.

for a middle

Explain per-field move tracking: which uses compile, which hit E0382 with a partially moved value, and how assigning the field on a mut binding makes the struct whole.

for a senior

Recognise E0509 on a type with Drop and choose a fix: borrow the field, clone it, or store it as an Option and take it, and question a Drop impl that exists for no reason.

for a principal

No lead decision lives here; at this level, explain how splitting a large config into owned sub-structs lets each worker take exactly the part it owns.

## What a partial move is A struct value is a group of fields stored together. Rust's move checker tracks initialisation **per field**, not just per variable. When you write `let endpoint = cfg.endpoint;` and `endpoint` is a `String` (not `Copy`), only that field moves: the `String` now belongs to `endpoint`, and `cfg.endpoint` is deinitialised. The other fields of `cfg` are untouched and fully owned by `cfg`. This state is called a **partial move**, and the struct is said to be **partially moved**. The Reference lists which places can be moved out of: variables that are not currently borrowed, temporaries, fields of such places when the containing type does not implement `Drop`, and the contents of a `Box`. That last condition about `Drop` is the one exception covered below. ## What still compiles and what does not Take `struct Config { endpoint: String, tags: Vec<String>, retries: u32 }` after `let endpoint = cfg.endpoint;`: | Use of `cfg` | Result with rustc 1.99.1 | |---|---| | `cfg.tags.len()` or `let r = &cfg.tags;` | compiles: the field is still initialised | | `let t = cfg.tags;` | compiles: a second, separate partial move | | `cfg.retries` | compiles: a `u32` is `Copy`, so reading it copies | | `println!("{:?}", cfg)` or `cfg.describe()` with `&self` | E0382 "borrow of partially moved value: `cfg`" | | `let whole = cfg;` or `run(cfg)` | E0382 "use of partially moved value: `cfg`" | The rule behind the table: anything that touches only live fields is fine, and anything that needs the struct as one value is refused, because part of that value now belongs to someone else. rustc adds a note naming the culprit: "partial move occurs because `cfg.endpoint` has type `String`, which does not implement the `Copy` trait". ## Making the struct whole again A partially moved struct can be repaired: 1. Declare it `let mut cfg`, because you are about to assign into it. 2. Assign a new value to the moved field: `cfg.endpoint = String::from("https://ingest.internal/v2");`. 3. Every field is initialised again, so `cfg` can be borrowed, printed or moved as a unit. The assignment drops nothing. The Reference says assignment runs the destructor of its left-hand operand only if it is initialised, and the moved-from field is not. Reading the moved field instead, for example `cfg.endpoint.clone()`, is just another use of a moved value and fails with E0382. ## Patterns move too, and references cannot - Destructuring is the same operation written as a pattern: `let Config { endpoint, .. } = cfg;` moves `endpoint` and leaves the rest of `cfg` usable. A `ref` binding in the pattern borrows instead; binding modes are covered with destructuring. - `let Config { endpoint, tags, retries } = cfg;` moves every field at once, which is the honest form when `cfg` is finished. - Through a reference you cannot partially move at all: `let e = r.endpoint;` with `r: &Config` fails with E0507, a borrow-checker topic rather than a move topic. ## Why `Drop` types forbid it: E0509 If `Config` has `impl Drop for Config`, its `drop(&mut self)` runs when `cfg` goes out of scope and may read any field. A struct with one field moved out would hand that destructor a hole. So rustc refuses the move outright: ```plaintext error[E0509]: cannot move out of type `Config`, which implements the `Drop` trait ``` The fixes rustc suggests are borrowing (`&cfg.endpoint`) or cloning. A design that needs to hand a field away from a `Drop` type can store it as an `Option<String>` and take it out, leaving `None`. ## In practice: handing pieces of a Config to a worker A log-ingestion service builds one `Config` and starts a worker that needs the endpoint string: - **Move** what the worker will own (`cfg.endpoint`), **copy** small `Copy` fields (`cfg.retries`), and keep using the rest (`cfg.tags`) on the current thread. - Reassign the moved field if `cfg` must later travel as a whole, or destructure it completely when it will not. - If several workers each need a slice of the configuration, splitting `Config` into owned sub-structs keeps each move obvious. At scope end the Reference guarantees that only the remaining fields are dropped: the moved `String` is freed later by the worker that received it, never twice.

  • What gets dropped when a partially moved `cfg` goes out of scope?
    Only the fields that are still initialised. The Reference states that after a partial move only the remaining fields are dropped. The moved `endpoint` belongs to whoever received it and is freed when that owner goes out of scope, so no field is freed twice and none leaks.
  • Why can't you move `endpoint` out of a `Config` that implements `Drop`?
    `Drop::drop` takes `&mut self` and runs when `cfg` goes out of scope, so it may read every field. Moving one out would leave it a struct with a missing field, so rustc rejects the move with E0509. Common fixes are borrowing the field, cloning it, or storing it as an `Option<String>` and taking it out.
  • Can you move two different fields out of `cfg`, one after the other?
    Yes. Each field is tracked separately, so `let e = cfg.endpoint; let t = cfg.tags;` compiles and leaves only `retries` in `cfg`. A full destructuring pattern, `let Config { endpoint, tags, retries } = cfg;`, says the same thing in one line and consumes `cfg` entirely.

  • Moving one field out makes every field of the struct unusable.
  • Reading a u32 field after the move fails too, because the struct was moved.
  • A partially moved struct can still be passed to a function taking &Config.
  • Calling cfg.endpoint.clone() after the move restores the field.
  • Every struct allows partial moves, including one that implements Drop.