有没有办法将现有结构用作枚举变体? [英] Is there a way to use existing structs as enum variants?
问题描述
我将枚举用于多态,类似于以下内容:
I'm using an enum for polymorphism, similar to the following:
enum MyType {
Variant1 { a: i32, b: i32 },
Variant2 { a: bool, b: bool },
}
是否有干净的方法来使用 Variant1
和 Variant2
的现有结构?我已完成以下操作:
Is there clean way to use existing structs for Variant1
and Variant2
? I've done the following:
struct Variant1 {
a: i32,
b: i32,
}
struct Variant2 {
a: bool,
b: bool,
}
enum MyType {
Variant1(Variant1),
Variant2(Variant2),
}
但感觉很笨重.我想知道是否有更好的方法来完成类似的事情.
but it feels pretty clunky. I was wondering if there's a better way to accomplish a similar thing.
推荐答案
有多个关于使枚举变体成为自己类型的 RFC:
There have been multiple RFCs about making enum variants their own type:
不幸的是,它们已被推迟或尚未决定,因为这不被视为语言优先事项.
Unfortunately, they have been postponed or not yet decided on as this is not considered a language priority.
这意味着现在,您提出的方式是拥有枚举变体类型的唯一方法.
This means that right now, the way you have proposed is the only way to have types for enum variants.
这篇关于有没有办法将现有结构用作枚举变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!