liveBook · Manning

Guard

As explained in Idiomatic Rust

A match guard is an if condition attached to a pattern that must also be true for the branch to match.

A match guard adds an `if` condition to a pattern; the branch matches only when both the pattern and condition match. The condition can use the matched value or another value. section 3.1.1

fn match_with_guard(value: i32, choose_first: bool) {
    match value {
        v if v == 1 && choose_first => {
            println!("First match: This value is equal to 1")
        }
        v if v == 1 && !choose_first => {
            println!("Second match: This value is equal to 1")
        }
        v if choose_first => {
            println!("First match: This value is equal to {v}")
        }
        v if !choose_first => {
            println!("Second match: This value is equal to {v}")
        }
        _ => println!("Fell through to the default case"),
    }
}

The value and `choose_first` conditions demonstrate guards selecting among branches, with a default case if none matches. section 3.1.1

How Idiomatic Rust covers it

How deep it goes
Defines the guard and demonstrates matched-value and separate-value conditions in a multi-branch example.
Examples
Demonstrates an `i32` value matched alongside a Boolean selector, with guarded branches and a fallback.
What you can do after
Apply guards to select match branches using the matched value or another value.
How it connects
Connects guards to pattern matching and match branches.

Also explained in

Compare how 4 books explain guard →

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.