简体   繁体   中英

Is it possible to bind all the struct members of an enum variant to a single variable?

Let say I define and instantiate an enum as follows:

enum MyEnum {
    EmptyVariant,
    TupleVariant(u8),
    StructVariant {
        key: u8,
        value: char,
    }
}

let instance = MyEnum::StructVariant{key: 8, value: 'a'};

Is it possible to match against this variant without destructuring? For example, instead of doing:

if let MyEnum::StructVariant{key, value} = instance {
    eprintln!("key, value = {}, {}", key, value);
}

I would rather write something like:

if let MyEnum::StructVariant{VARIANT_MEMBERS} = instance {
    eprintln!("key, value = {}, {}", VARIANT_MEMBERS.key, VARIANT_MEMBERS.value);
}

In this example, writing out the members of the struct variant is benign, but in the case where the variant has many members it makes the code difficult to read.

I don't think it is possible as of today.

I did see the following pattern, which in practice achieves what you asked for just with an extra intermediary type:

Instead place all the desired members of the StructVariant in an actual struct type, and have your enum use that struct as the only field of the StructVariant .

struct MyVariant {
    key: u8,
    value: char
}

enum MyEnum {
    EmptyVariant,
    TupleVariant(u8),
    StructVariant(MyVariant)
}

if let MyEnum::StructVariant(x) = instance {
    eprintln!("key, value = {}, {}", x.key, x.value);
}

This also proves handy when you want to pass the members of StructVariant around, to other functions or types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM