Reputation: 1975
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.
Upvotes: 6
Views: 1602
Reputation: 8084
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.
Upvotes: 5