From 16d25dbed720298cb6a99d61160fa94b846cf1e0 Mon Sep 17 00:00:00 2001 From: Vinh Tran Date: Tue, 29 Jul 2025 22:09:51 -0400 Subject: [PATCH] Clarify Matching Values section (#2833) --- src/pattern-matching/match.md | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/pattern-matching/match.md b/src/pattern-matching/match.md index c607b84c..01f24824 100644 --- a/src/pattern-matching/match.md +++ b/src/pattern-matching/match.md @@ -41,10 +41,24 @@ Key Points: - Match guards as a separate syntax feature are important and necessary when we wish to concisely express more complex ideas than patterns alone would allow. -- They are not the same as separate `if` expression inside of the match arm. An - `if` expression inside of the branch block (after `=>`) happens after the - match arm is selected. Failing the `if` condition inside of that block will - result in other arms of the original `match` expression being considered. +- Match guards are different from `if` expressions after the `=>`. An `if` + expression is evaluated after the match arm is selected. Failing the `if` + condition inside of that block won't result in other arms of the original + `match` expression being considered. In the following example, the wildcard + pattern `_ =>` is never even attempted. + +```rust,editable +#[rustfmt::skip] +fn main() { + let input = 'a'; + match input { + key if key.is_uppercase() => println!("Uppercase"), + key => if input == 'q' { println!("Quitting") }, + _ => println!("Bug: this is never printed"), + } +} +``` + - The condition defined in the guard applies to every expression in a pattern with an `|`. - Note that you can't use an existing variable as the condition in a match arm,