【发布时间】:2022-12-31 10:41:11
【问题描述】:
我的枚举有 40 多个变体,其中大约一半实现了该特征,但这里有一个更简单的例子:
trait CheeseBoard {
fn say_cheese(self);
}
struct Cheese {
name: String,
}
impl CheeseBoard for Cheese {
fn say_cheese(self) {
println!("I am {}", self.name);
}
}
struct Person {
name: String,
}
impl CheeseBoard for Person {
fn say_cheese(self) {
println!("{} says cheese!", self.name);
}
}
enum CheesyPerson {
Cheese(Cheese),
Person(Person),
UncheesyNonperson,
}
fn main() {
let _a = [
CheesyPerson::Cheese(Cheese {
name: "Gouda".into(),
}),
CheesyPerson::Person(Person {
name: "Peer".into(),
}),
CheesyPerson::UncheesyNonperson,
];
todo!("Call say_cheese on items in _a where the enum variant has exactly one field that implements the CheeseBoard trait.")
}
【问题讨论】:
-
如果只有一半的变体具有实现该特征的字段,那么您对另一半做了什么?
-
您在寻找
match声明吗?for v in _a { match v { CheesyPerson::Cheese(x) => x.say_cheese(), CheesyPerson::Person(x) => x.say_cheese(), _ => {} } }? -
@Shepmaster 我认为 OP 希望避免列出所有变体的样板。
-
@ChayimFriedman 也许吧!然而,OP没有明确说,当我试图假设他们的意思并以某种方式弄错时,我被太多的 SO 海报大喊大叫。
-
没有办法在 Rust 中做到这一点,比如说,编写一个只为您编写代码的宏。
标签: rust