Skip to content

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

Closed
@huonw

Description

@huonw

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),
    _ => {}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions