Skip to content

Commit fb6eeb6

Browse files
committed
Document _ in bindings
Fixes #25786
1 parent 9748574 commit fb6eeb6

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/doc/trpl/patterns.md

+32
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,38 @@ This ‘destructuring’ behavior works on any compound data type, like
282282
[tuples]: primitive-types.html#tuples
283283
[enums]: enums.html
284284

285+
# Ignoring bindings
286+
287+
You can use `_` in a pattern to disregard the value. For example, here’s a
288+
`match` against a `Result<T, E>`:
289+
290+
```rust
291+
# let some_value: Result<i32, &'static str> = Err("There was an error");
292+
match some_value {
293+
Ok(value) => println!("got a value: {}", value),
294+
Err(_) => println!("an error occurred"),
295+
}
296+
```
297+
298+
In the first arm, we bind the value inside the `Ok` variant to `value`. But
299+
in the `Err` arm, we use `_` to disregard the specific error, and just print
300+
a general error message.
301+
302+
`_` is valid in any pattern that creates a binding. This can be useful to
303+
ignore parts of a larger structure:
304+
305+
```rust
306+
fn coordinate() -> (i32, i32, i32) {
307+
// generate and return some sort of triple tuple
308+
# (1, 2, 3)
309+
}
310+
311+
let (x, _, z) = coordinate();
312+
```
313+
314+
Here, we bind the first and last element of the tuple to `x` and `z`, but
315+
ignore the middle element.
316+
285317
# Mix and Match
286318

287319
Whew! That’s a lot of different ways to match things, and they can all be

0 commit comments

Comments
 (0)