Rust如何对枚举封装的不同结构体向量按公共字段过滤
问题根因
Rust 枚举本身是独立类型,其内部变体的公共字段不会自动暴露到枚举的顶层作用域。你定义的id字段分别属于TransactionOrderA和TransactionOrderB两个结构体,TransactionsEnum枚举本身并没有定义id字段,因此直接访问e.id会触发编译错误。
解决方案
方案1:为枚举实现公共字段的访问方法(最常用)
给TransactionsEnum实现一个id()方法,内部通过模式匹配取出所有变体的id字段,之后你就可以在迭代时直接调用该方法获取值:
impl TransactionsEnum { pub fn id(&self) -> i64 { match self { Self::TransactionOrderA(order) => order.id, Self::TransactionOrderB(order) => order.id, } } }
修改过滤逻辑为调用该方法即可正常编译:
fn transactions_filter( transactions_vector: Vec<TransactionsEnum>, x: i64, ) -> Vec<TransactionsEnum> { transactions_vector .into_iter() .filter(|e| e.id() >= x) .collect() }
方案2:重构数据结构,把公共字段抽到顶层
如果你的所有交易类型公共字段不止id一个,可以调整结构,把公共字段都放到外层结构体里,枚举只存各类型特有的字段:
#[derive(Deserialize, Debug, Serialize, Clone)] pub struct Transaction { pub id: i64, pub order_info: OrderInfo, } #[derive(Deserialize, Debug, Serialize, Clone)] pub enum OrderInfo { TypeA(OrderAInfo), TypeB(OrderBInfo), } // 只存A类型特有的字段 #[derive(Deserialize, Debug, Serialize, Clone)] pub struct OrderAInfo { pub accountID: String, } // 只存B类型特有的字段 #[derive(Serialize, Deserialize, Debug, Clone)] pub struct OrderBInfo { pub time: DateTime<Utc>, }
这种结构下你可以直接访问Transaction实例的id字段,不需要额外的匹配逻辑,更适合公共字段较多的场景。
内容的提问来源于stack exchange,提问作者ender maz
相关产品推荐
相关产品推荐

