Skip to content

Pattern bindings of structure variant fieldsΒ #2158

Open
@mathstuf

Description

@mathstuf

Currently, the following is a syntax error:

enum MyEnum {
    StructVariant {
        a: String,
        b: u64,
    },
}

fn matcher(e: MyEnum) {
    match e {
        MyEnum::StructVariant v@{ .. } => {
            // do something with `v.a` and `v.b`.
        },
    }
}
error: expected one of `::`, `=>`, `if`, or `|`, found `v`                                                                                                                                                                                                                                                                    
  --> src/lib.rs:10:31
   |
10 |         MyEnum::StructVariant v@{ .. } => {
   |                              -^ unexpected token
   |                              |
   |                              expected one of `::`, `=>`, `if`, or `|` here

(Side note, why are { and ( not listed in the expected list?)

When a struct variant has many fields, many of which get used in some match arm, the arm tends to get unwieldy very quickly without resorting to trs vrbl nms.

I also want to avoid making it a 1-tuple variant over another struct because that means giving a name to the structure, exporting it, and documenting it ( andsince its only purpose is to give the variant something capture-able, the struct docstring will basically be either a duplicate or "see this variant").

Open questions (with some gut-level answers of my own):

  • What is the type of v above? IMO, it should be unnameable (like a closure), but still potentially implement default traits such as Clone, Copy, Sync, and Send (though another thought makes me think: who can receive this unnamed type other than by a trait object)? This means it probably cannot implement Any as well.
  • Can it be returned out of the match or if let? I think so. It's still an unnameable type, so it cannot be returned other than through impl Trait or Box<Trait>.
  • Is this a syntax ambiguity? I'm not seeing an obvious one at least.
  • Is it applicable to tuple variants as well?

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions