From bbc2056694f2fd4f631fb1b7d74c47ffe200b036 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Wed, 7 Oct 2015 16:41:15 -0400 Subject: [PATCH] Comment on shadowing with patterns Fixes #28687 --- src/doc/trpl/patterns.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/doc/trpl/patterns.md b/src/doc/trpl/patterns.md index a365732fe9b..bce147cc71f 100644 --- a/src/doc/trpl/patterns.md +++ b/src/doc/trpl/patterns.md @@ -23,6 +23,31 @@ match x { This prints `one`. +There’s one pitfall with patterns: like anything that introduces a new binding, +they introduce shadowing. For example: + +```rust +let x = 'x'; +let c = 'c'; + +match c { + x => println!("x: {} c: {}", x, c), +} + +println!("x: {}", x) +``` + +This prints: + +```text +x: c c: c +x: x +``` + +In other words, `x =>` matches the pattern and introduces a new binding named +`x` that’s in scope for the match arm. Because we already have a binding named +`x`, this new `x` shadows it. + # Multiple patterns You can match multiple patterns with `|`: -- 2.44.0