skip to content

Destructuring and Bindings

Patterns also appear in let and function parameters, and whether a binding moves, copies or borrows depends on binding modes. Interviewers ask what a pattern does to a value.

on this pageshow

questions

4

In Rust, what does `let Config { host, port: listen_port, .. } = cfg;` bind, and where else can such patterns appear?

level: juniorimportance: must knowfreq 58%

answer

  1. the left of = is a pattern
  2. field shorthand vs field: new_name
  3. .. once, and last in a struct
  4. _ binds nothing; _name still binds
  5. parameters, closures and for loops

basics

~20 s

The struct pattern binds host to the field of that name, binds the port field under the name listen_port, and .. ignores every other field. The same patterns work in function and closure parameters and in for loops.

solid answer

~50 s

A `let` takes a pattern, not just a name. In a struct pattern `host` is shorthand for `host: host`, `port: listen_port` binds that field under a new name, and `..` at the end ignores every field not named; leave both out and rustc reports E0027, "pattern does not mention field". Tuples destructure by position, `let (first, .., last) = t;`, and patterns nest, so `tls: Some(cert)` reaches inside an `Option` (which makes the pattern refutable, and a plain `let` refuses that). The same patterns go in function parameters such as `fn endpoint((host, port): (&str, u16))`, in closure parameters such as `|&(_, (x, y))|`, and in `for` loops. `_` matches without binding, so nothing moves; `_cert` is a real binding whose underscore only silences the unused-variable warning. Binding a `String` field out of an owned `cfg` moves it.

code

rust · 25 lines
rust
#![allow(dead_code)]

#[derive(Debug)]
struct Config { host: String, port: u16, tls: Option<String>, retries: u8 }

fn load_config() -> Config {
    Config { host: "db.internal".into(), port: 5432, tls: Some("ca.pem".into()), retries: 3 }
}

// A pattern in parameter position: the tuple is taken apart on entry.
fn endpoint((host, port): (&str, u16)) -> String {
    format!("{host}:{port}")
}

fn main() {
    let cfg = load_config();
    // Shorthand `host`, renamed `port: listen_port`, `..` ignores tls and retries.
    let Config { host, port: listen_port, .. } = cfg;
    println!("{}", endpoint((&host, listen_port)));

    // A nested pattern in a closure parameter: &(label, (x, y)).
    let labels = vec![("origin", (0, 0)), ("corner", (3, 4))];
    let total: i32 = labels.iter().map(|&(_, (x, y))| x + y).sum();
    println!("total = {total}");
}

go deeper

for a junior

Recall the three pieces of a struct pattern: field shorthand, field: new_name and a trailing .., and that the same patterns work in let, parameters, closures and for loops.

for a middle

Explain E0027, why .. may appear once, and why _ binds nothing while _name is a real binding that moves a non-Copy field.

for a senior

Show you can read a destructuring line and say which fields were moved, copied or never touched, and spot an underscore-prefixed name that moved a field nobody meant to move.

for a principal

There is little to decide here; the lead angle is review hygiene, such as preferring a destructuring let over a string of field accesses when it makes the moved and ignored fields visible.

## The left side of a `let` is a pattern In Rust, `let x = value;` is the simplest case of a more general rule: the part between `let` and `=` is a **pattern**, and the value on the right is matched against it. A plain name such as `x` is an **identifier pattern** that matches anything and binds all of it. Struct, tuple and nested patterns match the *shape* of the value and bind only the pieces they name. This is **destructuring**: taking a value apart into separate variables in one statement. ```rust let Config { host, port: listen_port, .. } = cfg; ``` After this line `host` and `listen_port` are ordinary local variables. ## Struct patterns: shorthand, renaming and `..` A **struct pattern** names the type and lists fields inside braces: - **Field shorthand.** `host` alone means `host: host`: match the field `host` and bind it to a variable called `host`. - **Renaming.** `port: listen_port` matches the field `port` and binds it to `listen_port`. Whatever follows the colon is itself a pattern, so `tls: Some(cert)` or `limits: Limits { max, .. }` nest one pattern inside another. - **The rest pattern `..`.** It stands for "every field I did not name" and binds none of them. In a struct pattern it must come **last**, with no trailing comma. - **Every field accounted for.** Without `..`, a struct pattern must mention every field. `let Config { host } = cfg;` on a four-field struct fails with **E0027**, "pattern does not mention field `port`", and rustc suggests either listing the field, `port: _`, or `..`. ## Tuples, tuple structs and nesting Tuple and tuple-struct patterns match **by position**: `let (w, h) = size;` or `let Celsius(t) = reading;`. The rest pattern works there too and may sit anywhere, but only once per pattern: | Pattern | Matches | Binds | |---|---|---| | `(a, b)` | a 2-tuple | both elements | | `(a, ..)` | any tuple with at least one element | the first | | `(.., z)` | any tuple with at least one element | the last | | `(first, .., last)` | a tuple of two or more | first and last | | `(x, .., y, ..)` | nothing | rejected: "`..` can only be used once per tuple pattern" | Patterns nest to any depth: `(name, (x, y))` takes apart a pair whose second element is itself a pair. Slice and array patterns such as `[first, .., last]` follow the same idea and are covered with slices. ## Where else patterns appear The same pattern grammar is used wherever Rust binds a name: 1. `let` statements. 2. **Function parameters**: `fn endpoint((host, port): (&str, u16)) -> String` receives one tuple and unpacks it on entry; the caller still passes a single argument. 3. **Closure parameters**: `labels.iter().map(|&(_, (x, y))| x + y)` destructures each `&(&str, (i32, i32))` item. 4. **`for` loops**: `for (i, line) in lines.iter().enumerate()` destructures each `(usize, &String)` pair. 5. `match` arms, `if let`, `while let` and `let`-`else`, which also accept patterns that can fail. The first four positions require patterns that **always match**, so `tls: Some(cert)` in a `let` is rejected with E0005; refutability is its own question. ## `_`, `_name` and what a binding does to the value Destructuring an **owned** value binds by value: a `Copy` field such as `port: u16` is copied, and a non-`Copy` field such as `host: String` is **moved** out of `cfg`, after which the moved field (and `cfg` as a whole) cannot be used. Two look-alike patterns behave differently here: - `_` is the **wildcard pattern**. It matches one field or element and binds nothing, so it neither copies, moves nor borrows. `let Config { tls: _, .. } = cfg;` leaves `cfg` fully usable. - `_cert` is an ordinary **identifier pattern**. The leading underscore only tells the `unused_variables` lint not to warn; the value is still bound, so `tls: _cert` moves the `Option<String>` out, and a later `cfg.tls` fails with E0382. - `..` behaves like `_` for every remaining field: it binds nothing. The rules for partial moves, and how to borrow instead of moving, are covered with ownership; the binding-mode questions show how to get references out of a pattern. ## Common slips - Treating `..` like struct update syntax: in a pattern it ignores fields, it does not fill them from `Default`. - Expecting a struct pattern to skip unnamed fields silently: without `..` it is E0027. - Writing `_unused` to "ignore" a large field and then wondering why the struct was moved.

  • Why does `let Config { host } = cfg;` fail when `Config` has more fields, and what are the three fixes?
    A struct pattern must account for every field, so rustc reports E0027, "pattern does not mention field `port`". You can list the field (`host, port`), ignore it explicitly (`port: _`), or end the pattern with `..` to ignore every field you did not name. rustc's own help suggests all three.
  • Can `..` sit anywhere in a struct pattern, the way it can in a tuple pattern?
    No. In a struct pattern `..` must be the last item with no trailing comma; `Config { .., host }` is rejected with "`..` must be at the end and cannot have a trailing comma". In a tuple pattern it may come first, in the middle or last, as in `(first, .., last)`, but only once per pattern.
  • Does a tuple pattern in a function parameter change how callers call the function?
    No. `fn endpoint((host, port): (&str, u16))` still takes one argument of type `(&str, u16)`; the pattern only decides how the body names its parts. The pattern must be irrefutable, so `Some(x)` cannot appear there.

  • In a pattern, `..` fills the unnamed fields with their default values.
  • A struct pattern can leave out fields it does not need without `..`.
  • `_cert` and `_` are the same wildcard; the underscore prefix means ignore.
  • Patterns only work in `match`, never in `let` or a parameter list.
  • Destructuring an owned struct always copies its fields, even a `String`.
open as a page

In Rust, what do `x` and `y` bind in `for (i, &(x, y)) in points.iter().enumerate()` over a `Vec<(f64, f64)>`, and what changes without the `&`?

level: middleimportance: should knowfreq 45%

basics

~10 s

iter() yields &(f64, f64), and the reference pattern &(x, y) matches that reference and dereferences it, so x and y are f64 copies. Without the &, the default binding mode makes them &f64 borrows.

open as a page

Why does rustc reject `let Config { host, tls: Some(cert), .. } = load_config();` with E0005, and where must a Rust pattern be irrefutable?

level: middleimportance: should knowfreq 50%

basics

~20 s

The nested Some(cert) cannot match a Config whose tls is None, so the whole pattern is refutable, and let accepts only patterns that always match. Function parameters, closure parameters and for loops have the same rule.

open as a page

In Rust, why does `match self.state { State::Retrying { mut attempts, .. } => attempts += 1, _ => {} }` leave the stored count unchanged, and how do you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

self.state is a place of type State, not a reference, so binding starts in move mode and mut attempts copies the u32 into a new mutable local. Match on &mut self.state, or write ref mut attempts, to bind a &mut u32 instead.

open as a page