【发布时间】:2023-03-03 08:53:23
【问题描述】:
我有一个特征Foo,有一些实现,还有一个枚举Foos,每个实现都有一个变体。我希望能够将我的枚举转换为Box<dyn Foo>。
这是我目前的解决方案:
trait Foo {}
struct FooA {}
impl Foo for FooA {}
struct FooB {}
impl Foo for FooB {}
struct FooC {}
impl Foo for FooC {}
enum Foos {
A(FooA),
B(FooB),
C(FooC),
}
impl Foos {
fn into_box(self) -> Box<dyn Foo> {
match self {
Foos::A(foo) => Box::new(foo),
Foos::B(foo) => Box::new(foo),
Foos::C(foo) => Box::new(foo),
}
}
}
它有效,但into_enum 中有很多样板。随着变体数量的增加,功能也会增加。有没有更简单的方法来做到这一点?感觉应该是单排!
【问题讨论】:
-
"感觉应该是单排!"主要意见?如果你愿意,你可以为 Rust 创建 RFC。
-
另外,为什么不
impl Foo for Foos? -
@Stargateur
Foo有很多方法,我不想对每个枚举变体进行匹配。 -
是的,我认为有一个关键字在为此做准备,但宏仍然可以很好地完成这项工作。