diff options
| author | bors <bors@rust-lang.org> | 2015-05-02 20:47:32 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2015-05-02 20:47:32 +0000 |
| commit | 0d7d3ec9d2b314af0188a820c58fbd95ee905793 (patch) | |
| tree | 4e6ebc84d34930b1ee4a5a830bbc9d5f43689ffc /src/doc/trpl | |
| parent | 5574029b68e4a66864c4eaff8553cc8086117d56 (diff) | |
| parent | df18642b1ad80369cefc0cbe626e5b0096654938 (diff) | |
| download | rust-0d7d3ec9d2b314af0188a820c58fbd95ee905793.tar.gz rust-0d7d3ec9d2b314af0188a820c58fbd95ee905793.zip | |
Auto merge of #25058 - steveklabnik:gh25008, r=huonw
Fixes #25008
Diffstat (limited to 'src/doc/trpl')
| -rw-r--r-- | src/doc/trpl/patterns.md | 34 |
1 files changed, 31 insertions, 3 deletions
diff --git a/src/doc/trpl/patterns.md b/src/doc/trpl/patterns.md index 97a3dfe8a76..266c1cafdee 100644 --- a/src/doc/trpl/patterns.md +++ b/src/doc/trpl/patterns.md @@ -70,8 +70,7 @@ This prints `something else` # Bindings -If you’re matching multiple things, via a `|` or a `...`, you can bind -the value to a name with `@`: +You can bind values to names with `@`: ```rust let x = 1; @@ -82,7 +81,36 @@ match x { } ``` -This prints `got a range element 1`. +This prints `got a range element 1`. This is useful when you want to +do a complicated match of part of a data structure: + +```rust +#[derive(Debug)] +struct Person { + name: Option<String>, +} + +let name = "Steve".to_string(); +let mut x: Option<Person> = Some(Person { name: Some(name) }); +match x { + Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a), + _ => {} +} +``` + +This prints `Some("Steve")`: We’ve bound the inner `name` to `a`. + +If you use `@` with `|`, you need to make sure the name is bound in each part +of the pattern: + +```rust +let x = 5; + +match x { + e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e), + _ => println!("anything"), +} +``` # Ignoring variants |
