Skip to content

Comment on shadowing with patterns #28893

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 8, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/doc/trpl/patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,31 @@ match x {

This prints `one`.

There’s one pitfall with patterns: like anything that introduces a new binding,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if it's worth having a section on shadowing? It is interesting to point out that Rust typically allows shadowing, and patterns are just a special case.

It's ALSO interesting (perhaps) to point out that you cannot shadow a constant or enum variant name.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We talk about it in the variable bindings section, but this is a question that people ask about with patterns specifically, so I felt it was worth re-calling it out.

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 `|`:
Expand Down