Skip to content

Commit 0d7d3ec

Browse files
committed
Auto merge of #25058 - steveklabnik:gh25008, r=huonw
Fixes #25008
2 parents 5574029 + df18642 commit 0d7d3ec

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

src/doc/trpl/patterns.md

+31-3
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,7 @@ This prints `something else`
7070

7171
# Bindings
7272

73-
If you’re matching multiple things, via a `|` or a `...`, you can bind
74-
the value to a name with `@`:
73+
You can bind values to names with `@`:
7574

7675
```rust
7776
let x = 1;
@@ -82,7 +81,36 @@ match x {
8281
}
8382
```
8483

85-
This prints `got a range element 1`.
84+
This prints `got a range element 1`. This is useful when you want to
85+
do a complicated match of part of a data structure:
86+
87+
```rust
88+
#[derive(Debug)]
89+
struct Person {
90+
name: Option<String>,
91+
}
92+
93+
let name = "Steve".to_string();
94+
let mut x: Option<Person> = Some(Person { name: Some(name) });
95+
match x {
96+
Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),
97+
_ => {}
98+
}
99+
```
100+
101+
This prints `Some("Steve")`: We’ve bound the inner `name` to `a`.
102+
103+
If you use `@` with `|`, you need to make sure the name is bound in each part
104+
of the pattern:
105+
106+
```rust
107+
let x = 5;
108+
109+
match x {
110+
e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e),
111+
_ => println!("anything"),
112+
}
113+
```
86114

87115
# Ignoring variants
88116

0 commit comments

Comments
 (0)