diff options
| author | Steve Klabnik <steve@steveklabnik.com> | 2015-07-06 12:27:32 -0400 |
|---|---|---|
| committer | Steve Klabnik <steve@steveklabnik.com> | 2015-07-06 12:27:32 -0400 |
| commit | fb6eeb6ce8980c23daec0361e61dfe406f535eb5 (patch) | |
| tree | 49a7b0ccd05071466b28f36dcce668bca6807b3f | |
| parent | 9748574271847c1d6e65b71eca175cfcac9361f5 (diff) | |
| download | rust-fb6eeb6ce8980c23daec0361e61dfe406f535eb5.tar.gz rust-fb6eeb6ce8980c23daec0361e61dfe406f535eb5.zip | |
Document _ in bindings
Fixes #25786
| -rw-r--r-- | src/doc/trpl/patterns.md | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/src/doc/trpl/patterns.md b/src/doc/trpl/patterns.md index 7a1f8bf21bf..9603eec7aca 100644 --- a/src/doc/trpl/patterns.md +++ b/src/doc/trpl/patterns.md @@ -282,6 +282,38 @@ This ‘destructuring’ behavior works on any compound data type, like [tuples]: primitive-types.html#tuples [enums]: enums.html +# Ignoring bindings + +You can use `_` in a pattern to disregard the value. For example, here’s a +`match` against a `Result<T, E>`: + +```rust +# let some_value: Result<i32, &'static str> = Err("There was an error"); +match some_value { + Ok(value) => println!("got a value: {}", value), + Err(_) => println!("an error occurred"), +} +``` + +In the first arm, we bind the value inside the `Ok` variant to `value`. But +in the `Err` arm, we use `_` to disregard the specific error, and just print +a general error message. + +`_` is valid in any pattern that creates a binding. This can be useful to +ignore parts of a larger structure: + +```rust +fn coordinate() -> (i32, i32, i32) { + // generate and return some sort of triple tuple +# (1, 2, 3) +} + +let (x, _, z) = coordinate(); +``` + +Here, we bind the first and last element of the tuple to `x` and `z`, but +ignore the middle element. + # Mix and Match Whew! That’s a lot of different ways to match things, and they can all be |
