liveBook · Manning

Pattern matching

As explained in Idiomatic Rust

Pattern matching is a language feature that selects behavior by testing a value against structurally defined patterns and optionally binding parts of the value.

Pattern matching is a Rust runtime control-flow feature. A `match` tests a value against patterns, selects an arm, and can bind or destructure data. Every possibility must be covered, either explicitly or with a catch-all. It is a language feature, not itself a design pattern. section 3.1

Patterns let a match express several kinds of decisions:

  • Match `Option` cases such as `Some` and `None`, binding a contained value when needed. section 3.1.1
  • Match literals, alternatives, ranges, tuple positions, enum variants, and struct fields. section 3.1.1
  • Add guards for extra conditions. The compiler can flag unreachable arms and reject patterns with incompatible types. section 3.1.1
Listing 3.1 Pattern matching an Option
fn some_or_none<T>(option: &Option<T>) {
    match option {
        Some(_v) => println!("is some!"),       #1
        None => println!("is none :("),
    }
}

A small `Option` match demonstrates handling both cases. section 3.1.1

Use matching to unpack data and handle cases clearly, including nested structs and enums. It can replace combinations of `if`/`else` statements; exhaustive cases make code easier to reason about, though they do not prevent logic errors. section 3.3

How Idiomatic Rust covers it

How deep it goes
Explains exhaustive matches, bindings, guards, and value and structure patterns through Rust examples and compiler diagnostics.
Examples
Uses Option cases, integer ranges, tuple destructuring, enum variants, struct fields, and guarded matches.
What you can do after
Apply exhaustive matches to unwrap Option values, destructure data, select behavior, and handle cases clearly.
How it connects
Connects to Option, Result, enums, structs, tuples, functional programming, and the `?` operator.

Also explained in

Compare how 12 books explain pattern matching →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.