skip to content

In Rust, why does `match cfg.token { Some(t) => ..., None => ... }` leave that `Option<String>` field unusable, and how do you match without moving?

level: middleimportance: should knowfreq 55%

answer

  1. patterns bind by value
  2. Some(t) takes the String out
  3. a partial move of the Option
  4. match on a reference instead
  5. as_ref, as_deref, take

basics

~20 s

The pattern Some(t) binds t by value, so the String moves out of the Option and cfg.token is partially moved; later use fails with E0382 whichever arm ran. Match on &cfg.token or use cfg.token.as_deref() to borrow instead.

solid answer

~40 s

A by-value binding in a pattern moves whatever it binds. In `match cfg.token { Some(t) => ... }` the scrutinee is the field itself, not a copy, so `t` takes the `String` out of the `Option` and rustc records a partial move of `cfg.token`. That is decided at compile time, so a later `cfg.token.is_some()` fails with E0382 "borrow of partially moved value: `cfg.token`" even if the value was `None` at run time; `cfg.endpoint` is unaffected. To look without taking, match on `&cfg.token` (the default binding mode then makes `t` a `&String`), write `Some(ref t)`, or call `cfg.token.as_ref()` for `Option<&String>` or `as_deref()` for `Option<&str>`. If you really need the owned string and can mutate `cfg`, `cfg.token.take()` moves it out and leaves `None`. A `Some(_)` arm binds nothing and moves nothing.

code

rust · 14 lines
rust
struct Config {
    endpoint: String,
    token: Option<String>,
}

fn main() {
    let cfg = Config { endpoint: String::from("https://ingest.internal/v1"), token: Some(String::from("s3cr3t")) };
    match cfg.token {
        Some(t) => println!("auth with {} chars", t.len()),
        None => println!("anonymous"),
    }
    println!("{}", cfg.endpoint);
    println!("{:?}", cfg.token.is_some());
}

go deeper

for a junior

Know that Some(t) in a match or if let moves a String out of an owned Option, and that matching on a reference avoids it.

for a middle

Explain why the move is decided at compile time regardless of the arm taken, and choose among a borrowed match, ref, as_ref, as_deref and take by what the code needs.

for a senior

In review, prefer as_deref or a borrowed match over clone() for read-only checks, and accept take() only where leaving None is a documented state of the struct.

for a principal

No lead decision lives here; at this level, explain how an Option field that is handed off once, such as a credential, should document its after-take state in the type's API.

## Patterns bind by value unless told otherwise A `match` or `if let` compares a **scrutinee** (the expression after `match`) against **patterns**. When a pattern contains a name, such as `t` in `Some(t)`, that name is a **binding**, and by default it binds **by value**. For a `Copy` payload like `Option<u32>` that copies. For `Option<String>` it moves: the `String` inside the `Option` becomes owned by `t`. The scrutinee `cfg.token` is a **place expression**, the field itself, not a temporary copy of it. So the move comes out of `cfg.token`, and rustc tracks it the same way it tracks moving a struct field: `cfg.token` is now **partially moved** (its payload is gone), and `cfg` as a whole is partially moved too. `cfg.endpoint` stays usable. ## The partial move a match leaves behind ```plaintext error[E0382]: borrow of partially moved value: `cfg.token` 9 | Some(t) => println!("auth with {} chars", t.len()), | - value partially moved here ... 13 | println!("{:?}", cfg.token.is_some()); | ^^^^^^^^^ value borrowed here after partial move ``` Two points surprise people: - The move belongs to the `Some(t)` arm, but the check is **static**: after the `match`, `cfg.token` is *possibly* moved, so every later use is rejected, even on runs where the token was `None`. - `if let Some(t) = token { ... }` is the same pattern with one arm and behaves identically. rustc's help offers the smallest fix: `Some(ref t)`, which binds by reference. ## Ways to match without moving | Form | Type of `t` | `cfg.token` afterwards | |---|---|---| | `match cfg.token { Some(t) => ... }` | `String` (owned) | partially moved | | `match &cfg.token { Some(t) => ... }` | `&String` | intact | | `match cfg.token { Some(ref t) => ... }` | `&String` | intact | | `cfg.token.as_ref()` | `Option<&String>` | intact | | `cfg.token.as_deref()` | `Option<&str>` | intact | | `cfg.token.take()` (needs `mut` access) | `Option<String>` (owned) | `None` | Matching on `&cfg.token` works because of **default binding modes**: when a pattern without `&` meets a reference, bindings inside it become references. The detailed rules belong with destructuring. `Option::as_ref` and `Option::as_deref` are the method forms; `as_deref` goes one step further through `Deref`, which suits functions that take `&str`. `Option::take` is different in kind: it needs `&mut` access, moves the value out and stores `None` in its place, so the field is never left half-moved. It is the right tool when the code genuinely needs ownership but the struct must stay whole. ## Patterns that never move - The wildcard `_` and `Some(_)` bind nothing, so `match token { Some(_) => ..., None => ... }` leaves `token` fully usable. - `None`, literals and `..` bind nothing either. - A binding of a `Copy` payload, such as `Some(n)` on `Option<u32>`, copies rather than moves. - An identifier pattern for the whole scrutinee, `match token { x => ... }`, is the opposite case: it moves the entire `Option`, and a later use reports "borrow of moved value: `token`". The same rule applies wherever a pattern appears. `let Some(t) = cfg.token else { return };` moves the string exactly like the `match` does, and a later `cfg.token` read fails with the same E0382. `matches!(cfg.token, Some(_))` expands to a `match` with a wildcard, so it moves nothing and leaves `cfg.token` intact. Moving a payload out from behind a reference, as in `match *r { Some(t) => ... }` with `r: &Option<String>`, is a separate error, E0507, which belongs with borrow-checker diagnostics. ## Choosing in an ingestion pipeline A worker reads its `Config`, whose `token: Option<String>` holds an optional credential: 1. **Only checking or printing the token**: borrow it with `as_deref()` or match on `&cfg.token`. Nothing moves and nothing is cloned. 2. **Consuming the whole config**: let it move. Destructure `cfg` fully, or match on `cfg.token` when `cfg` will not be used again. 3. **Handing the credential to a worker while `cfg` stays alive**: use `cfg.token.take()`. `None` now means the token was handed off, which the type's documentation should state. Cloning the token just to satisfy the checker is the weakest choice: it allocates a second copy of a secret and hides the question of who owns it.

  • Why does `match token { x => ... }` also make `token` unusable?
    An identifier pattern binds the whole scrutinee by value, so `x` takes ownership of the entire `Option<String>`. A later use reports E0382 "borrow of moved value: `token`", a full move rather than a partial one. Binding by reference, with `ref x` or by matching on `&token`, leaves it in place.
  • What is the difference between `as_ref()` and `as_deref()` on an `Option<String>`?
    `Option::as_ref` turns `&Option<String>` into `Option<&String>`. `Option::as_deref` goes one step further through `Deref` and yields `Option<&str>`. Both borrow, so the field stays intact; `as_deref` is usually the more convenient one because most functions take `&str`.
  • When is `cfg.token.take()` the right tool?
    When the code really needs the owned `String` but `cfg` must stay usable, for example handing a one-time credential to a worker. `Option::take` needs `&mut` access, moves the value out and stores `None`, so the struct is never partially moved. The cost is that `None` now also means 'already handed off', which the type should document.

  • A match only inspects its scrutinee, so it can never move anything.
  • If the token was None at run time, cfg.token is still usable after the match.
  • Some(_) moves the String just like Some(t) does.
  • as_ref() on an Option<String> clones the String into a new Option.
  • if let Some(t) = token takes the value out and leaves None behind.