Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 132 ยท Operators and Control Flow

Patterns in Depth

Master Rust patterns - destructuring structs, enums, tuples and slices, refutable vs irrefutable patterns, ref and ref mut, @ bindings, let-else and the matches! macro.

You have already used patterns without calling them that. The (index, planet) in a for loop, the Some(x) in if let, the arms of a match: all of them are patterns. A pattern is a description of the shape of a value. When Rust meets a pattern it checks whether the value fits that shape, and if it does, it can pull the pieces out into new variables at the same time. That second part is called destructuring.

Patterns are everywhere in Rust: let statements, function parameters, match arms, if let, while let, for loops, closures. Learning them well makes a lot of code shorter and safer. This lesson goes through every kind of pattern you will meet, explains the difference between patterns that can fail and ones that cannot, and ends with let ... else and the matches! macro. The previous lesson showed for and while let; the next one uses these patterns on Option.

Patterns are not just for match

A plain let is already a pattern. These two lines are destructuring in action:

Rust Destructuring tuples and structs in let

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In let (name, age) = ... the pattern (name, age) has the shape "a pair", and the two names bind to the two parts. For a struct, Point { x, y } binds variables with the same names as the fields; x: horizontal picks a different variable name. Function parameters are patterns too: fn show(&(a, b): &(i32, i32)) is legal, and so are closure parameters like |(k, v)| ....

Refutable and irrefutable patterns

Some patterns can never fail: (name, age) fits every pair, x fits everything. These are irrefutable. Others can fail: Some(x) does not fit None, and 1..=5 does not fit 9. These are refutable.

The rule is simple, and the compiler enforces it:

  • let, function parameters and for loops need irrefutable patterns, because there is no "else" branch to go to.
  • if let, while let, let ... else and match arms accept refutable patterns, because they say what to do when the pattern does not fit.

What happens when you break the rule?

Rust A refutable pattern in a plain let (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler answers with:

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

The compiler also suggests let ... else (shown below). The other fix is if let, which does something only when the pattern fits.

Literals, ranges, wildcards and rest

You have seen literal and range patterns in match. Three more tools help you ignore what you do not need:

  • _ ignores one value and binds nothing.
  • _name binds the value but tells the compiler not to warn if it is unused.
  • .. ignores all the remaining fields or elements.
Rust Ignoring parts of a value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

One subtle point: _ does not bind, so it does not move the value either. let _ = make_string(); drops the string immediately, whereas let _unused = make_string(); keeps it alive until the end of the scope. This difference matters for guards and locks, which you will meet in the Drop and RAII lesson.

Destructuring enums and nesting

Patterns can be nested as deeply as the data is. Here is an enum whose variants hold structs and tuples, matched with patterns that reach inside:

Rust Nested patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Look at how specific patterns (a literal inside a struct pattern) come before general ones, exactly the ordering rule from the match lesson. Also see c @ 'a'..='z': the @ binding tests a range and keeps the value. Without @ you could bind or test a sub-pattern, but not both at once.

Binding modes: references, ref and ref mut

When you match on a reference, Rust automatically binds by reference. This is called default binding modes, and it is why the previous example never moved a String out of the &Event. Matching &Config with Config { host, port, .. } gave host: &String and port: &u16.

Sometimes you hold an owned value but want to bind by reference without moving it. The keyword ref does that, and ref mut borrows mutably:

Rust ref and ref mut

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In modern Rust you rarely need ref; writing let (first, _) = &pair; or if let Some(inner) = &mut value gives the same result and reads better. You will still see ref in older code. The related symbol & in a pattern does the opposite: it matches a reference and takes the value out of it. That is why for &x in &numbers yields plain i32 values (works for Copy types):

Rust
let numbers = [3, 1, 4];
let mut largest = 0;
for &n in &numbers {
    if n > largest {
        largest = n;
    }
}

In the 2024 edition, Rust is stricter about mixing explicit &, ref or mut with default binding modes. If you write the reference-style (&value on the right side) you will not hit the restrictions. The edition guide lists the exact rules; the short advice is to let default binding modes do the work.

Slice patterns

Patterns can describe the layout of an array or slice. [first, .., last] fits any slice with at least two elements; [a, b] fits only slices of exactly two:

Rust Slice patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

tail @ .. binds the rest of the slice to tail, which is itself a slice (&[i32]). That makes recursive list processing easy to write, though in practice an iterator is shorter and faster for sums. The compiler also checks these patterns for exhaustiveness: the four arms above cover lengths 0, 1, 2 and 2-or-more, and removing one would be an E0004 error. Slice patterns are especially nice for parsing command words, as in ["add", name, qty], which you will use in the project lessons.

if let, let chains and let-else

When one pattern matters, if let is lighter than match:

Rust if let, else and a let chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A let chain joins several let patterns and ordinary boolean conditions with &&, so you do not need three levels of nested if let. It is stable only in the 2024 edition (Rust 1.88), which is what our editor uses.

The other helper is let ... else (stable since Rust 1.65). It binds variables in the surrounding scope when the pattern fits, and runs an else block when it does not. The else block must leave the current flow: return, break, continue or panic!.

Rust let-else for early returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Compare this with nested if let: the happy path stays at one indentation level, and each failure is dealt with right where it occurs. It is the recommended style for validation at the top of a function. For error values you will soon prefer the ? operator, introduced in The ? Operator.

Blocks as expressions and shadowing patterns

Every block { ... } is an expression: its value is the last line without a semicolon. Combined with shadowing (a new let with the same name), this gives you a tidy way to compute a value in several steps and then freeze it, so nothing can change it by accident.

Rust Freezing a value by shadowing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The rule of thumb: use mut when the same value changes over time (a counter in a loop), and use shadowing when you transform a value into a new one, possibly of a different type. The block form let x = { ...mutable work...; x }; limits the mutable phase to a few lines. It pairs well with let ... else: bind with let ... else for the part that can fail, then shadow the name with the cleaned-up value.

matches!: a pattern as a bool

Sometimes you only want a yes/no answer: is this value of that shape? The matches! macro evaluates to true or false, and it supports |, ranges and guards:

Rust The matches! macro

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

matches!(value, pattern) is the idiomatic replacement for a match whose arms are just true and false. It is also the way to test an enum variant, because enums do not implement == unless you derive PartialEq.

Where patterns trip people up

  • A name in a pattern is a new binding, not a comparison. match n { limit => ... } matches everything and shadows the outer limit. Use a constant (const LIMIT: i32 = 10;, then LIMIT =>) or a guard.
  • Moving out of a borrow. Matching on &value and binding a non-Copy field by value is an error (E0507: cannot move out of a shared reference). Bind by reference or clone.
  • Bindings in or-patterns must agree. In Some(1) | Some(n), every alternative must bind the same names with the same types.
  • Guards do not count for exhaustiveness. A final unguarded arm is always required.
  • Forgetting that .. is not a wildcard for a missing variant. It only skips fields or elements, so Shape::Circle(..) matches a circle with any data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement is an error because the pattern is refutable?

    Some(n) does not fit None, so a plain let cannot use it (E0005). Use if let, let-else or match.
  2. 2. What does [first, .., last] match?

    The two named elements must exist, so the slice needs at least two items; .. covers zero or more in between.
  3. 3. What must the else block of let Some(x) = opt else { ... }; do?

    After let-else, x must be bound in the surrounding scope, so the else block cannot fall through. It must leave the flow.
  4. 4. What is the difference between let _ = f(); and let _guard = f();?

    _ does not bind, so the temporary is dropped at once. A named binding such as _guard keeps the value alive; the leading underscore only silences the unused warning.
  5. 5. Which is the shortest correct way to ask whether opt is Some(n) with n > 10?

    matches! accepts a pattern with an optional guard and returns a bool.

Summary

  • A pattern describes a shape and optionally binds names to its parts; it appears in let, parameters, match, if let, while let and for.
  • Irrefutable patterns (cannot fail) are required by let, parameters and for; refutable patterns (can fail) belong in match, if let, while let and let ... else.
  • Use _ for one ignored value, .. for all remaining fields or elements, and name @ pattern to test and bind at once.
  • Matching a reference binds by reference automatically; ref and ref mut do the same on owned values, but are rarely needed today.
  • Slice patterns such as [first, .., last] and [head, tail @ ..] destructure arrays and slices.
  • let ... else keeps the happy path unindented; let chains (if let ... && ...) are available in edition 2024; matches! turns a pattern into a bool.

Next: Option and Handling Absence