

























April 17, 2026, 9:57pm 1
Is there a way to assign a struct constant to an enum variant?
Something like this, maybe:
struct Properties {
thingone: bool,
thingtwo: u32,
}
enum MyItems {
ItemOne = Properties { thingone: false, thingtwo: 7 },
ItemTwo = Properties { thingone: true, thingtwo: 13 },
}
To later retrieve the fields of that struct for a specific enum variant?
Enum variants are not values, they're more like types. The type associated with an enum variant can be a struct type, but not a struct value.
This can be confusing because enums in some languages are used for constants, where each constant is assigned a value.
1 Like
kyouma April 17, 2026, 10:31pm 3
I'm not sure this is the best idea, but maybe create a function on the enum?
struct Properties {
thingone: bool,
thingtwo: u32,
}
enum MyItems {
ItemOne,
ItemTwo,
}
impl MyItems {
fn props(&self) -> Properties {
match self {
MyItems::ItemOne => Properties { thingone: false, thingtwo: 7 },
MyItems::ItemTwo => Properties { thingone: true , thingtwo: 13 },
}
}
}
3 Likes
quinedot April 17, 2026, 10:35pm 5
Another guess at what you may want:
struct Properties {
thingone: bool,
thingtwo: u32,
}
impl Properties {
const ITEM_ONE: Self = Self { thingone: false, thingtwo: 7 };
const ITEM_TWO: Self = Self { thingone: true, thingtwo: 13 };
}
Perhaps paired with an actual enum ala @kyouma's reply.
kpreid April 17, 2026, 10:35pm 6
This is a reasonable idea. However, it is more common to write separate methods for each property:
impl MyItems {
fn thingone(self) -> bool {
match self {
MyItems::ItemOne => false,
MyItems::ItemTwo => true,
}
}
fn thingtwo(self) -> u32 {
match self {
MyItems::ItemOne => 7,
MyItems::ItemTwo => 13,
}
}
}
This way, only the needed information is returned, in one step instead of two. But, if the Properties struct is useful to the application, there is nothing wrong with doing that instead, or in addition. In that case, you might also want to consider returning a reference:
impl MyItems {
fn props(self) -> &'static Properties {
match self {
MyItems::ItemOne => &Properties { thingone: false, thingtwo: 7 },
MyItems::ItemTwo => &Properties { thingone: true , thingtwo: 13 },
}
}
}
This has the advantage that the Properties struct won't ever be copied around, which might have consistently better performance (depending very much on how big Properties actually is, and how it is used).
4 Likes
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。