Rust中如何为嵌套结构体添加泛型类型?
解决Rust中嵌套结构体持有不同Config类型的代码重复问题
我遇到一个场景:嵌套在其他结构体中的Model结构体需要持有两种不同的Config对象——ModelConfig或SeedConfig,这两个Config除少量字段外几乎一致。目前我只能通过定义两个具体结构体(SeedModel和ModelModel)来切换config字段,这导致所有方法和trait实现都出现重复。
现有代码
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct MetaModel { pub model: Model } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct Model { pub name: String, pub config: Option<ModelConfig> }
已尝试的方案
1. 泛型方案
将Model和MetaModel改为泛型结构体,但泛型类型会向上传递,导致定义极为复杂,而且创建父结构体时缺乏必要上下文,最终出现错误:the type parameter C is not constrained by the impl trait, self type, or predicates unconstrained type parameter。
尝试的代码:
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct MetaModel<C> { pub model: Model<C> } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct Model<C> { pub name: String, pub config: Option<C> }
2. trait对象方案
定义Config trait并使用trait对象,但Serde无法序列化trait对象,此方案不可行。
尝试的代码:
pub trait Config {} pub struct ModelConfig; impl Config for ModelConfig {} pub struct SeedConfig; impl Config for SeedConfig {} #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct Model { pub name: String, pub config: Option<Box<dyn Config>> }
期望实现的效果
希望能让单个Model结构体同时支持持有SeedConfig或ModelConfig,比如在trait实现中可以灵活返回对应类型的Model:
impl OtherTrait for Model { type Value = Model; fn build_model(&self, m: DerivedMeta) -> Result<Self::Value, &'static str> { Ok(Model { // 可持有SeedConfig或ModelConfig }) } }
内容的提问来源于stack exchange,提问作者seve
相关产品推荐
相关产品推荐

