gpt4 book ai didi

rust - 如何根据传入的枚举值使结构实例具有不同类型的字段?

转载 作者:行者123 更新时间:2023-12-03 11:47:10 27 4
gpt4 key购买 nike

我想为结构创建不同的“ flavor ”。这意味着,根据我要传入结构的构造函数的枚举,我将获得结构的版本,其“ flavor ”特征的类型取决于该枚举值。我知道我必须为结构的字段指定一个单一的类型,但是如果我想根据要传递给构造函数的值来更改该类型,该怎么办?我只能使用特质来做这样的事情吗?

pub struct ChocolateFlavor {
coco: u32,
}

pub struct VanillaFlavor {
bean: u32,
}

pub struct IceCream {
flavor: (), //should be able to be ChocholateFlavor or VanillaFlavor
}

pub enum Flavors {
Vanilla,
Chocholate,
}

impl IceCream {
pub fn new(input_type: Flavors) -> Self {
match input_type {
Flavors::Vanilla => input = VanillaFlavor,
Flavors::Chocholate => input = ChocolateFlavor,
}
let mut new_icecream = LabeledInput { flavor: input };
new_icecream
}
}

fn main() {
//give me a chocholate ice cream
let mut my_chocholate = IceCream::new(Flavors::Chocolate);
//give me a vanilla ice cream
let mut my_vanilla = IceCream::new(Flavors::Vanilla);
}

最佳答案

您可以将枚举与值一起使用

enum FlavorData {
ChocolateFlavor { coco: u32 },
VanillaFlavor { bean: u32 },
}

pub struct IceCream {
flavor: FlavorData,
}

pub enum Flavors {
Vanilla,
Chocolate,
}

impl IceCream {
pub fn new(input_type: Flavors) -> Self {
let flavor = match input_type {
Flavors::Vanilla => FlavorData::VanillaFlavor { bean: 10 },
Flavors::Chocolate => FlavorData::ChocolateFlavor { coco: 20 },
};
IceCream { flavor: flavor }
}
}

fn main() {
//give me a chocholate ice cream
let mut my_chocolate = IceCream::new(Flavors::Chocolate);
//give me a vanilla ice cream
let mut my_vanilla = IceCream::new(Flavors::Vanilla);
}

关于rust - 如何根据传入的枚举值使结构实例具有不同类型的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65295106/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com