Patterns that Bind

Patterns that Bind in Rust: A watchmaker who opens a pocket watch does not tip the parts onto the bench.

The Analogy: The Watchmaker's Parts Tray

A watchmaker who opens a pocket watch does not tip the parts onto the bench. Each piece goes into a shallow depression in a parts tray, and every depression is labelled: balance wheel, mainspring, click, crown wheel. Taking the movement apart and naming its pieces is one motion, not two. When the watchmaker later reaches for "the mainspring", there is no searching and no guessing -- the name was assigned at the moment the part came out.

The tray is cut for one calibre. Lower a movement from the wrong family into it and the pieces do not land where the labels say they should, which is itself the answer to the question "is this the movement I think it is?". The fit is the test. A tray that accepts the movement has also, in the same instant, told you what everything in front of you is called.

Not every job needs every part. To replace a mainspring you open the case, lift out the spring, and leave the rest exactly where it sits. The tray has depressions you never fill, and that is not an oversight -- it is the point. Naming only what you are about to work with is how the bench stays readable.

And sometimes you want both at once: a tag on the whole movement and labels on the parts you pulled. The tag says "this is the 1948 calibre from the Tuesday batch"; the labels say "and here is its mainspring, and its click". A Rust pattern does exactly this trio. It tests the shape of a value, names the parts you asked for, and -- with @ -- can name the whole thing at the same time.


Syntax or Core Structure

A pattern is not only a question. Wherever a value carries data, the pattern that matches it can name that data, and those names are in scope for the arm's body.

enum Currency {
    Gbp,
    Eur,
    Usd,
}

enum Payment {
    Cash,
    Card { last4: String, currency: Currency },
    Voucher(u32),
    Transfer { sort: String, account: String },
}

struct Parcel {
    id: u32,
    kg: u32,
    tracked: bool,
}

fn code(c: &Currency) -> &'static str {
    match c {
        Currency::Gbp => "GBP",
        Currency::Eur => "EUR",
        Currency::Usd => "USD",
    }
}

fn describe(p: &Payment) -> String {
    match p {
        Payment::Cash => String::from("cash, no reference"),
        Payment::Card { last4, currency } => {
            format!("card ending {last4} in {}", code(currency))
        }
        Payment::Voucher(pence) => format!("voucher worth {pence}p"),
        Payment::Transfer { sort, account } => format!("transfer {sort}/{account}"),
    }
}

fn main() {
    let payments = [
        Payment::Cash,
        Payment::Card { last4: String::from("4242"), currency: Currency::Gbp },
        Payment::Card { last4: String::from("1881"), currency: Currency::Eur },
        Payment::Card { last4: String::from("9004"), currency: Currency::Usd },
        Payment::Voucher(500),
        Payment::Transfer { sort: String::from("04-00-04"), account: String::from("12345678") },
    ];

    for p in &payments {
        println!("{}", describe(p));
    }

    let point = (3, -7);
    let (x, y) = point;
    println!("\nx = {x}, y = {y}");

    let parcel = Parcel { id: 91, kg: 4, tracked: true };
    let Parcel { id, kg, .. } = &parcel;
    println!("parcel {id} weighs {kg} kg, tracked {}", parcel.tracked);

    let n = 42;
    match n {
        small @ 0..=9 => println!("{small} is a single digit"),
        big @ 10..=99 => println!("{big} has two digits"),
        other => println!("{other} is larger"),
    }
}

Output:

cash, no reference
card ending 4242 in GBP
card ending 1881 in EUR
card ending 9004 in USD
voucher worth 500p
transfer 04-00-04/12345678

x = 3, y = -7
parcel 91 weighs 4 kg, tracked true
42 has two digits

Four different binding shapes appear here. Payment::Card { last4, currency } uses field shorthand: naming a field in a struct pattern creates a variable with the same name holding that field. Payment::Voucher(pence) binds positionally, because a tuple variant has no field names to borrow. let (x, y) = point destructures a tuple in a plain let, with no match in sight. And small @ 0..=9 uses the @ operator to test a range and keep the value that satisfied it.

Two details are worth pausing on. let Parcel { id, kg, .. } = &parcel; matches against a reference, so id and kg are &u32 rather than u32 -- the parcel is not taken apart, only read -- which is why parcel.tracked still works on the next line. And the .. is not decoration: without it the compiler refuses the pattern outright.

error[E0027]: pattern does not mention field `tracked`
 --> src/main.rs:9:9
  |
9 |     let Parcel { id, kg } = &parcel;
  |         ^^^^^^^^^^^^^^^^^ missing field `tracked`
  |
help: include the missing field in the pattern
help: if you don't care about this missing field, you can explicitly ignore it

(The two help: blocks normally arrive with a suggested rewrite of the line underneath each one; those are trimmed here.) The rule is that a struct pattern must account for every field, either by naming it or by covering it with ... That sounds like bureaucracy until a field is added to Parcel and you want to know which patterns should now think about it -- which is the same bargain match makes with enum variants.


Technical Depth: How a Pattern Names What It Matches

The catalogue

PatternWhat it bindsNotes
xthe whole valueirrefutable, and it shadows any outer x
_nothing at allirrefutable, and it does not move the value
_namethe whole valuea real binding that moves; the underscore only silences the unused warning
(a, b)both elements of a 2-tupleirrefutable for that tuple type
Point { x, y }both fields, under their own namesfield shorthand
Point { x: col, y: row }both fields, under new namesread x: col as "field x into col"
Point { x, .. }only x.. covers the remaining fields, present and future
Some(v)the payloadrefutable: None does not match
Wrapper(a, b)tuple-struct positionspositional, because there are no field names
n @ 1..=9the whole value, and tests the range@ reads "and also call it"
[first, .., last]the two ends of a sliceneeds a length of at least 2
[head, tail @ ..]the first element and the rest as a subslicetail is a &[T], not a Vec
&valuethe pointee, dereferencing on the wayrarely written now that match ergonomics exist
ref va reference to the matched placethe pre-ergonomics spelling; kept for compatibility

An or-pattern -- two alternatives separated by a vertical bar -- may also bind, but every alternative has to bind the same names at the same types, because the arm body is compiled once. Shape::Circle { r } | Shape::Ring { r, .. } => ... is fine; adding a name to only one side gives error[E0408], "variable is not bound in all patterns", naming the variable that only one alternative supplies.

Binding modes: by reference, by mutable reference, by value

The same pattern behaves differently depending on what you match it against. When a reference is matched against a pattern that is not itself a reference pattern, Rust flips the default binding mode -- this is match ergonomics, and it is why modern Rust code almost never writes ref.

struct Job {
    id: u32,
    tag: String,
    attempts: u32,
}

fn main() {
    let mut job = Job { id: 7, tag: String::from("resize"), attempts: 0 };

    let Job { id, tag, .. } = &job;
    println!("by ref   id {id} tag {tag} len {}", tag.len());

    let Job { attempts, .. } = &mut job;
    *attempts += 1;
    println!("bumped   attempts {}", job.attempts);

    let Job { tag, .. } = job;
    println!("by value tag {tag}");
}

Output:

by ref   id 7 tag resize len 6
bumped   attempts 1
by value tag resize

Three matches, three binding modes, one unchanged pattern shape. Against &job, tag is a &String, so job is merely borrowed and remains whole. Against &mut job, attempts is a &mut u32, which is why the body needs *attempts += 1 -- and the borrow ends at that statement, which is what lets the very next line read job.attempts. Against job itself, tag is a String moved out of the struct, leaving job partially moved and unusable as a whole afterwards.

The @ operator: test and keep

A range or a nested pattern proves something about a value but normally throws the value away. @ keeps both.

enum Event {
    Click { x: u32, y: u32 },
    Key(char),
}

fn triage(n: u32) -> String {
    match n {
        0 => String::from("zero"),
        d @ 1..=9 => format!("{d} is a single digit"),
        t @ 10..=99 => format!("{t} has two digits, tens {}", t / 10),
        big => format!("{big} is big"),
    }
}

fn label(e: Event) -> String {
    match e {
        Event::Click { x: col @ 0..=99, y } => format!("click in the left band, col {col}, row {y}"),
        Event::Click { x, y } => format!("click at {x},{y}"),
        Event::Key(c @ 'a'..='z') => format!("lowercase key {c}"),
        Event::Key(c) => format!("other key {c}"),
    }
}

fn main() {
    for n in [0, 7, 42, 1500] {
        println!("{}", triage(n));
    }

    println!();

    let events = [
        Event::Click { x: 12, y: 4 },
        Event::Click { x: 800, y: 90 },
        Event::Key('r'),
        Event::Key('!'),
    ];
    for e in events {
        println!("{}", label(e));
    }
}

Output:

zero
7 is a single digit
42 has two digits, tens 4
1500 is big

click in the left band, col 12, row 4
click at 800,90
lowercase key r
other key !

Without @, the second arm of triage would have to be 1..=9 => String::from("a single digit"), because the digit itself was never named. Writing n if (1..=9).contains(&n) is the alternative, and it states the range twice -- once in the guard and once in the reader's head. x: col @ 0..=99 shows the same trick reaching into a field: the field is renamed and constrained in one clause.

Ignoring on purpose: _, _name, and ..

fn main() {
    let text = String::from("kept");
    let _ = text;
    println!("still here: {text}");

    let owned = String::from("gone");
    let taken = owned;
    println!("taken: {taken}");

    let tup = (1, 2, 3, 4, 5);
    let (first, .., last) = tup;
    println!("first {first} last {last}");

    let pair = (String::from("left"), String::from("right"));
    let (_, second) = pair;
    println!("second {second}");
}

Output:

still here: kept
taken: gone
first 1 last 5
second right

let _ = text; looks like it should consume text, and it does not: _ is not a binding, so nothing is moved and text prints on the next line. let taken = owned; is the contrast -- a real name, a real move. In let (_, second) = pair; only the second String leaves the tuple; the first is never named, so it stays inside the partially-moved pair and is dropped when the scope ends. And (first, .., last) is how you take the ends of a five-element tuple without inventing three names you will never use.

Refutable and irrefutable patterns

A pattern is irrefutable if it matches every possible value of its type, and refutable if some value can slip past it. (x, y) against a 2-tuple is irrefutable. Some(port) against an Option is refutable, because None exists. Positions that have nowhere to go when a match fails accept only irrefutable patterns: let, function parameters, closure parameters, and the loop variable of a for.

error[E0005]: refutable pattern in local binding
 --> src/main.rs:3:9
  |
3 |     let Some(port) = maybe_port;
  |         ^^^^^^^^^^ pattern `None` not covered

(rustc follows this with a note that let bindings require an irrefutable pattern and a help suggesting let ... else; both are trimmed here.) The refutable positions are match arms, if let, while let, and the let ... else form, all of which have somewhere to send a value that does not fit.

Patterns are not only for match

fn distance((x1, y1): (i32, i32), (x2, y2): (i32, i32)) -> f64 {
    let dx = (x2 - x1) as f64;
    let dy = (y2 - y1) as f64;
    (dx * dx + dy * dy).sqrt()
}

fn port_or_default(raw: Option<&str>) -> u16 {
    let Some(text) = raw else {
        return 8080;
    };
    text.parse().unwrap_or(8080)
}

fn main() {
    println!("{:.3}", distance((0, 0), (3, 4)));
    println!("{}", port_or_default(Some("9000")));
    println!("{}", port_or_default(Some("nine")));
    println!("{}", port_or_default(None));

    let pairs = [("host", "example.test"), ("port", "9000")];
    for (key, value) in &pairs {
        println!("{key} = {value}");
    }
}

Output:

5.000
9000
8080
8080
host = example.test
port = 9000

Every one of those is a pattern doing the same job in a different position. (x1, y1): (i32, i32) is a parameter pattern -- the caller passes one tuple, the body sees two numbers. let ... else accepts a refutable pattern precisely because the else block is required to diverge, so there is no path on which text is unbound. And for (key, value) in &pairs destructures each item as it arrives, which is why iterating a map or a zip almost never needs .0 and .1.


Real World Example: Turning Meter Readings into Alerts

A cold-chain monitor receives readings of four different shapes from depot sensors and has to turn each one into an alert with a severity, a site and a human sentence. Every field the sentence needs is inside the reading; the patterns are what get it out.

enum Severity {
    Info,
    Warning,
    Critical,
}

impl Severity {
    fn tag(&self) -> &'static str {
        match self {
            Severity::Info => "INFO",
            Severity::Warning => "WARN",
            Severity::Critical => "CRIT",
        }
    }
}

struct Alert {
    severity: Severity,
    site: String,
    text: String,
}

enum Reading {
    Temperature { site: String, celsius: i32, sensor: u32 },
    Pressure { site: String, bar: u32, sensor: u32 },
    Door { site: String, open: bool },
    Offline { site: String, since_minutes: u32, note: Option<String> },
}

fn assess(r: &Reading) -> Alert {
    match r {
        Reading::Temperature { site, celsius: c @ 28..=34, sensor } => Alert {
            severity: Severity::Warning,
            site: site.clone(),
            text: format!("sensor {sensor} reads {c}C, over the 27C ceiling"),
        },
        Reading::Temperature { site, celsius: c @ 35..=999, sensor } => Alert {
            severity: Severity::Critical,
            site: site.clone(),
            text: format!("sensor {sensor} reads {c}C, clear the aisle"),
        },
        Reading::Temperature { site, celsius, .. } => Alert {
            severity: Severity::Info,
            site: site.clone(),
            text: format!("{celsius}C, within range"),
        },
        Reading::Pressure { site, bar: 0, sensor } => Alert {
            severity: Severity::Critical,
            site: site.clone(),
            text: format!("sensor {sensor} reads zero bar, the line is empty"),
        },
        Reading::Pressure { site, bar, .. } => Alert {
            severity: Severity::Info,
            site: site.clone(),
            text: format!("{bar} bar"),
        },
        Reading::Door { site, open: true } => Alert {
            severity: Severity::Warning,
            site: site.clone(),
            text: String::from("cold store door left open"),
        },
        Reading::Door { site, open: false } => Alert {
            severity: Severity::Info,
            site: site.clone(),
            text: String::from("door closed"),
        },
        Reading::Offline { site, since_minutes: m @ 0..=5, .. } => Alert {
            severity: Severity::Info,
            site: site.clone(),
            text: format!("offline {m} min, inside the retry window"),
        },
        Reading::Offline { site, since_minutes, note: Some(note) } => Alert {
            severity: Severity::Critical,
            site: site.clone(),
            text: format!("offline {since_minutes} min: {note}"),
        },
        Reading::Offline { site, since_minutes, note: None } => Alert {
            severity: Severity::Critical,
            site: site.clone(),
            text: format!("offline {since_minutes} min, no note left"),
        },
    }
}
fn main() {
    let readings = [
        Reading::Temperature { site: String::from("hull-1"), celsius: 21, sensor: 4 },
        Reading::Temperature { site: String::from("hull-1"), celsius: 31, sensor: 4 },
        Reading::Temperature { site: String::from("leeds-2"), celsius: 42, sensor: 7 },
        Reading::Pressure { site: String::from("leeds-2"), bar: 6, sensor: 9 },
        Reading::Pressure { site: String::from("leeds-2"), bar: 0, sensor: 9 },
        Reading::Door { site: String::from("hull-1"), open: false },
        Reading::Door { site: String::from("york-3"), open: true },
        Reading::Offline { site: String::from("york-3"), since_minutes: 3, note: None },
        Reading::Offline {
            site: String::from("york-3"),
            since_minutes: 90,
            note: Some(String::from("power work booked")),
        },
        Reading::Offline { site: String::from("hull-1"), since_minutes: 120, note: None },
    ];

    let mut critical = 0;
    let mut warnings = 0;

    for r in &readings {
        let a = assess(r);
        match &a.severity {
            Severity::Critical => critical += 1,
            Severity::Warning => warnings += 1,
            Severity::Info => {}
        }
        println!("{}  {:<8} {}", a.severity.tag(), a.site, a.text);
    }

    println!("\n{critical} critical and {warnings} warnings out of {} readings", readings.len());
}

Output:

INFO  hull-1   21C, within range
WARN  hull-1   sensor 4 reads 31C, over the 27C ceiling
CRIT  leeds-2  sensor 7 reads 42C, clear the aisle
INFO  leeds-2  6 bar
CRIT  leeds-2  sensor 9 reads zero bar, the line is empty
INFO  hull-1   door closed
WARN  york-3   cold store door left open
INFO  york-3   offline 3 min, inside the retry window
CRIT  york-3   offline 90 min: power work booked
CRIT  hull-1   offline 120 min, no note left

4 critical and 2 warnings out of 10 readings

Every arm is a small extraction. The pattern declares which shape it handles and, in the same breath, names the fields that arm's sentence needs. sensor is bound in four arms and deliberately dropped in two, and the arms that drop it say so out loud with .. rather than by omission. Nothing in the bodies calls an accessor, tests a tag, or unwraps anything -- by the time a body runs, the data it needs is already sitting in local variables with useful names.

@ is doing real work in the temperature bands. celsius: c @ 28..=34 states the band once and still hands the arm the number, so the message can quote the actual reading instead of a vague "over the ceiling". The alternative -- a bare 28..=34 arm that then has to read the field again -- either repeats the field access or repeats the range in a guard, and one of the two copies is where the next threshold change will be forgotten.

Literals and nested variants inside patterns move decisions out of the bodies entirely. bar: 0 decides "the line is empty" structurally. open: true and open: false split the door cases with no if anywhere. And note: Some(note) reaches through the Option in the same pattern that matched the variant, so an offline alert either has a note to quote or is a genuinely different arm. That is three conditionals that never had to be written, and three places a typo cannot hide.

Three honest limits. site.clone() allocates a fresh String for every alert; returning a borrowed &str tied to the reading's lifetime would avoid it, and that is a M6 technique. The bands are hard-coded, and 35..=999 in particular is a sentinel rather than a bound -- a reading of 1200C would fall through to the third arm and be reported as "within range", which is exactly the gap an open-ended range or a guard closes. And the arm count is the product of variants and bands, so a fifth reading type with three bands costs three arms; past a certain size the banding moves into a helper function and the match goes back to one arm per variant.


Common Mistakes

  1. Treating _ and _name as the same thing. They differ in the one way that matters: _ is not a binding, so nothing moves and nothing is kept alive, while _name is a full binding that owns the value until the end of its scope. With a lock guard this is the difference between a bug and correct code -- let _ = mutex.lock(); acquires the lock and drops the guard on the same line, releasing it immediately, whereas let _guard = mutex.lock(); holds it for the rest of the block. The underscore prefix silences the unused-variable warning; it does not change what the binding does.
  1. Writing a variable name in a pattern and expecting a comparison. let wanted = 3; match n { wanted => "hit", _ => "miss" } always reports "hit", because wanted in pattern position introduces a new binding that shadows the outer one and matches every value. The only hint is an unreachable_patterns warning on the _ arm. Compare with a guard -- x if x == wanted -- or make the value a const, which pattern position treats as a literal.
  1. Moving out of the scrutinee when you only wanted to read it. match payment { Payment::Voucher(pence) => pence, ... } on an owned payment is fine for a u32, but Payment::Card { last4, .. } => last4.len() moves the String out and leaves payment partially moved, so a later use is error[E0382], "borrow of partially moved value". Match on &payment and match ergonomics gives you &String bindings that read exactly the same in the body.
  1. Reaching for * to "get the value out" of a borrowed scrutinee. When p: &Payment and the bindings come out as references, the instinct is match *p. That asks to move the payload out of something you do not own, and the answer is error[E0507], "cannot move out of a shared reference". Either keep the reference bindings and call methods on them, or clone the one field you genuinely need to own.
  1. Putting .. anywhere other than the end of a struct pattern. Parcel { .., kg } does not parse: in a struct pattern .. means "and the remaining fields", it binds nothing, and it must come last with no trailing comma. Slice patterns are the ones where .. may sit in the middle, may appear as [first, .., last], and may be bound with rest @ ... The same two dots, two different jobs.
  1. Binding the same name twice in one pattern. Pair { left: x, right: x } is not a way to ask "are these two fields equal"; it is error[E0416], "identifier is bound more than once in the same pattern". A pattern assigns names, it does not check them against each other. Bind two names and compare them in a guard: Pair { left: a, right: b } if a == b.
  1. Giving the alternatives of an or-pattern different bindings. The arm body is compiled once, so every alternative must bind the same names at the same types. Shape::Circle { r } | Shape::Square { side } => ... fails with error[E0408], "variable is not bound in all patterns", and it names the variable only one side supplies. Rename the fields to a common binding where that makes sense, or write two arms.
  1. Using @ on data that would have to move twice. msg @ Message::Text(text) asks to own the whole message and own the String inside it, which cannot both be true. The compiler allows a binding alongside sub-bindings only when nothing needs to move -- Copy types, or bindings taken by reference. Match on &msg so both msg and text are references, or drop the @ and re-read the field from the outer value.
  1. Putting a refutable pattern where nothing can fail. for Some(x) in items reads like "iterate the ones that are Some", and it is error[E0005], "refutable pattern in for-loop binding" -- a for loop has nowhere to send an item that does not match. The same applies to let and to function parameters. Use for item in items with an if let inside, or items.iter().flatten() when you really do want to skip the empty ones.

Best Practices

  • Destructure once at the boundary rather than reading fields one at a time. let Config { host, port, .. } = &config; at the top of a function beats five config.field accesses scattered through it, and it documents in one line exactly what this function looks at.
  • Prefer field shorthand and rename only when the field name is wrong in context. Point { x, y } needs no explanation; Point { x: col, y: row } earns its extra words because col and row are what the surrounding code calls them.
  • Match against a reference by default. match &value, match self, match slice -- take ownership only when the arm genuinely needs to keep the data. Match ergonomics means the patterns look identical either way, so this costs nothing in readability.
  • Use .. for fields that are genuinely irrelevant, and name the ones you want to be told about. .. is a promise that new fields need no attention here. Where that promise is false, spell the fields out and let the E0027 error be your reviewer.
  • Reach for @ whenever the arm needs both the test and the value. n @ 1..=9 writes the range once. A bare range arm that then re-reads the field, or a guard that restates the bounds, writes it twice.
  • Reserve _name for values whose lifetime matters. Drop guards, join handles and #[must_use] results are the honest uses. If you only want to discard something, _ says so and moves nothing.
  • Use let ... else for the "one shape or bail" case. It keeps the happy path unindented and un-nested, which a one-armed match or an if let with a long body cannot.
  • Keep binding names short. The pattern above them already says which variant and which field they came from, so site beats reading_site_name and c is perfectly clear inside a three-line temperature arm.

Practice Exercises

  1. Destructure through two levels. Define struct Address { city: String, postcode: String } and struct Customer { name: String, address: Address, credit: Option<u32> }. Write fn label(c: &Customer) -> String that binds name, city and postcode in a single let pattern -- nested struct patterns, no intermediate variables -- while covering credit with .., and returns something like "ada -- London N1 9GU". Then write a second function that keeps credit in the pattern and uses one match with nested patterns to distinguish a customer with no credit line, one with a zero limit, and one with a positive limit.
  1. Bands with @. Write fn band(bytes: u64) -> String as a single match using @ on the inclusive ranges 0..=1023, 1024..=1_048_575 and 1_048_576..=1_073_741_823, plus a final catch-all. Each message must quote the band name and the value converted to the right unit, computed from the bound name. Test 0, 1023, 1024, 5_000_000 and 2_000_000_000, and check that no range bound appears more than once anywhere in the function.
  1. Slice patterns with a bound rest. Write fn summarise(words: &[&str]) -> String with arms for [], [one], [first, last], and [first, rest @ ..] -- the last one reporting first together with rest.len(). Confirm the match compiles with no _ arm, then swap the final two arms, compile again, and record the unreachable_patterns warning together with which arm it points at and why.
  1. Prove the three binding modes. Using the Job struct from the Technical Depth section, write three functions: fn tag_len(j: &Job) -> usize that binds tag through a pattern and returns its length; fn bump(j: &mut Job) that increments attempts through a pattern binding rather than through field access; and fn take_tag(j: Job) -> String that moves the tag out with a struct pattern. Call take_tag twice on the same value, record the exact error[E0382] text, then write a two-sentence comment naming which binding in which pattern performed the move.