skip to content

Structs, Enums and Patterns

Structs and enums are how Rust models data, and match takes them apart. Interviewers test methods, data-carrying variants, exhaustiveness and binding modes.

on this pageshow

explore

questions

19

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, why is Option<T> an ordinary enum rather than a nullable value, and why can't an Option<u64> be passed where a u64 is expected?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Option<T> is a plain library enum, enum Option<T> { None, Some(T) }, defined in core and imported by the prelude. Option<u64> is a different type from u64, so rustc rejects passing it (E0308) until code matches the value out.

open as a page

In Rust, how can one PaymentEvent enum hold unit, tuple and struct variants carrying different data, and how do you read it?

level: juniorimportance: must knowfreq 75%

basics

~20 s

A Rust enum lists variants that may each carry their own fields: none (unit), positional (tuple) or named (struct). Every variant builds a value of the one enum type, and the fields are read only by matching the variant.

open as a page

In Rust, why does a match over an OrderState enum that leaves out Cancelled fail with E0004, and what must every arm agree on?

level: juniorimportance: must knowfreq 80%

basics

~20 s

A Rust match must be exhaustive: rustc proves every value of the scrutinee's type is covered, so a missing OrderState::Cancelled arm is error E0004. Because match is an expression, every arm must also produce the same type.

open as a page

In Rust, how does an associated function such as `Thermostat::new` differ from a method, and how do you declare and use an associated const?

level: juniorimportance: must knowfreq 70%

basics

~20 s

An associated function has no self parameter, so it is called by path, Thermostat::new(18.5). A method has a self receiver and is called with a dot. An associated const sits in the impl block and is read as Self::MAX.

open as a page

In Rust, how do you choose between `self`, `&self` and `&mut self` for a method, and what does each leave the caller holding?

level: juniorimportance: must knowfreq 80%

basics

~20 s

Pick the weakest receiver the body needs: &self to read, &mut self to change fields in place, self to consume or convert. The caller keeps its value after the first two; self moves it away unless the type is Copy.

open as a page

In Rust, why does a u16 status-code match written with guards fail with E0004 when the same split into range patterns compiles?

level: middleimportance: must knowfreq 65%

basics

~20 s

Rust's exhaustiveness checker ignores guards: a guarded arm counts as covering nothing, so guard-only arms over a u16 leave every value uncovered. Range patterns such as 500..600 are patterns, so rustc can prove they cover the type.

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, how do explicit discriminants on a fieldless HttpStatus enum work with `as` casts, and why can't a u16 be cast back?

level: middleimportance: should knowfreq 45%

basics

~20 s

A unit-only enum may give variants values, Ok = 200; unspecified ones take the previous value plus one, starting at 0. HttpStatus::Ok as u16 reads the value, but 404u16 as HttpStatus is E0605, because most integers name no variant.

open as a page

In Rust, what do `c @ 400..=499` and `Some(Paid | Shipped)` do as match patterns, and when is `matches!` the better tool?

level: middleimportance: should knowfreq 50%

basics

~20 s

In Rust, c @ 400..=499 tests the value against the range and binds it to c; Some(Paid | Shipped) is a nested or-pattern matching either variant inside Some. matches!(value, pattern) returns a bool when you need only the test.

open as a page

In Rust, how does a `Celsius(f64)` newtype stop a Fahrenheit reading reaching `set_target`, and what does the wrapper cost you?

level: middleimportance: should knowfreq 55%

basics

~20 s

A tuple struct such as Celsius(f64) is a distinct type, so passing a Fahrenheit value where Celsius is expected fails with E0308, while a type alias compiles silently. The cost is code: no f64 methods or operators until you add them.

open as a page

In Rust, why is `base` still usable after `Thermostat { room: String::from("office"), ..base }` but not after `Thermostat { target: 23.0, ..base }`?

level: middleimportance: should knowfreq 50%

basics

~20 s

Struct 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.

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

A Rust ledger keeps a Vec<PaymentEvent> where only the rare Chargeback variant holds a 520-byte Evidence struct; why does every element take 528 bytes, and how do you shrink it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

An enum value is as large as its largest variant plus the tag, rounded up to its alignment, so every element pays for Chargeback. Boxing the payload, Chargeback(Box<Evidence>), keeps one pointer inline and drops the enum to 24 bytes.

open as a page

After a Refunded variant is added to a Rust OrderState enum, why does a match on (state, event) still compile, and how do you restructure it so rustc flags it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Rust's tuple match still compiles because a trailing _ covers every combination, including those with OrderState::Refunded. Name every state in the first position and keep wildcards only on the event side, so a new state fails with E0004.

open as a page

A Rust `Thermostat::summary(&self)` calls `self.sensor.into_report()`, where `into_report` takes `self`, and fails with E0507: why, and how do you fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A self receiver needs an owned Sensor, but summary only borrows the thermostat, and moving the field out would leave a hole. Fix it with a borrowing report(&self) on Sensor, a consuming into_summary(self) on Thermostat, or a deliberate clone.

open as a page

As a Rust team lead, would you forbid `_` arms in matches over your own enums, and how would you scope and enforce that rule?

level: principalimportance: should knowfreq 25%

basics

~20 s

On Rust enums a team owns and expects to grow, explicit arms usually pay off: a new variant breaks the build where a decision is needed. Enforce it with Clippy's wildcard_enum_match_arm, reasoned #[expect] exceptions, and exempt integers, strings and foreign enums.

open as a page

In Rust, why is Option<Option<bool>> one byte while Option<Option<&u64>> takes 16, and how does NonZeroU32 give an AccountId the same saving?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

None goes in a niche, a bit pattern the payload never holds. bool has 254 spares, so nested Options fit one byte; a reference has only null, so a second layer needs a tag. NonZeroU32 frees 0, so Option<AccountId> stays 4 bytes.

open as a page