Skip to content

@-pattern documentation in the book is a little misleading #25008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
huonw opened this issue Apr 30, 2015 · 1 comment · Fixed by #25058
Closed

@-pattern documentation in the book is a little misleading #25008

huonw opened this issue Apr 30, 2015 · 1 comment · Fixed by #25058

Comments

@huonw
Copy link
Member

huonw commented Apr 30, 2015

http://doc.rust-lang.org/book/patterns.html#bindings . Current text here for future triage purposes:

Bindings

If you’re matching multiple things, via a | or a ..., you can bind the value to a name with @:

let x = 1;

match x {
    e @ 1 ... 5 => println!("got a range element {}", e),
    _ => println!("anything"),
}

This prints got a range element 1.

The @ binding is more general than just | or ... patterns: it can be attached to literally any pattern, e.g.

let mut x: Option<SomeStruct> = ...;
match x {
    Some(SomeStruct { a_field: ref a @ Some(_), .. }) => {}
    Some(ref mut b @ SomeStruct { something_else: 5, .. }) => {},
    Some(SomeStruct { third_one: c @ &Ok(_) }) => {},
    _ => {}
}

Also, for |, the @ has to be attached to each alternative:

let x = 1;
match x {
    y @ 1...5 | y @ 10...15 => println!("{}", y),
    _ => {}
}
@pnkfelix
Copy link
Member

Or at least, the identifier y has to be bound in each alternative:

fn main() {
    #[derive(Debug)]
    struct Recur<'a>(u8, Option<&'a Recur<'a>>);
    let r1 = Recur(2, None);
    let r2 = Recur(1, Some(&r1));
    match r2 {
        ref y @ Recur(1, _) | Recur(_, Some(&ref y)) => {
            println!("{:?}", y);
        }
        _ => { println!("other"); }
    }
}

steveklabnik added a commit to steveklabnik/rust that referenced this issue May 2, 2015
steveklabnik added a commit to steveklabnik/rust that referenced this issue May 2, 2015
steveklabnik added a commit to steveklabnik/rust that referenced this issue May 2, 2015
bors added a commit that referenced this issue May 2, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants