Skip to content

Syntax for matching on a collection element is not obvious #19177

Closed
@mdinger

Description

@mdinger

The documentation should document how [] changes inside a match as opposed to outside of one. A quick browsing of the guides didn't find this noted anywhere:

fn main() {
    let array = ["a", "b"]; // `[]` denotes `array`
    let v = vec!["match_this", "1"];

    match v {
    //    ^ Change `v` to `v.as_slice()` to make this work. Hard to discover...

        // How does this work though? It appears like this is matching a slice
        // against an array and succeeding. It is not obvious that `[]` inside a
        // match is `slice` syntax and not `array` syntax

        // Now `[]` denotes slice...
        ["match_this", a] => println!("{}", a),
        _ => {},
    }
}

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