diff --git a/src/doc/trpl/patterns.md b/src/doc/trpl/patterns.md index 9603eec7aca712a8808ef6edde3d3647bbb251a3..1abd4ca6c2174fd1571c1c2a8c7402909a6c836d 100644 --- a/src/doc/trpl/patterns.md +++ b/src/doc/trpl/patterns.md @@ -112,26 +112,55 @@ match x { } ``` -# Ignoring variants +# Ignoring bindings -If you’re matching on an enum which has variants, you can use `..` to -ignore the value and type in the variant: +You can use `_` in a pattern to disregard the type and value. +For example, here’s a `match` against a `Result`: ```rust -enum OptionalInt { - Value(i32), +# let some_value: Result = 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. + +Similarly, you can use `..` in a pattern to disregard multiple values. + +```rust +enum OptionalTuple { + Value(i32, i32, i32), Missing, } -let x = OptionalInt::Value(5); +let x = OptionalTuple::Value(5, -2, 3); match x { - OptionalInt::Value(..) => println!("Got an int!"), - OptionalInt::Missing => println!("No such luck."), + OptionalTuple::Value(..) => println!("Got a tuple!"), + OptionalTuple::Missing => println!("No such luck."), } ``` -This prints `Got an int!`. +This prints `Got a tuple!`. # Guards @@ -282,38 +311,6 @@ 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`: - -```rust -# let some_value: Result = 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