我有一个如下的枚举:
enum Foo {
A(X),
B(Y),
C(Z),
}
Run Code Online (Sandbox Code Playgroud)
其中 X、Y 和 Z 是实现该方法的结构体bar()
我希望能够bar在Foo枚举上定义一个方法,以便它调用其内部值的相应方法。现在我有这个:
impl Foo {
pub fn bar() {
match self {
Foo::A(f) => { f.bar(); }
Foo::B(f) => { f.bar(); }
Foo::C(f) => { f.bar(); }
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果可能的话,如何使用枚举做得更好?
您可以使用特征对象,而不是使用枚举:
trait Bar { fn bar(&self); }
struct X;
impl Bar for X { fn bar(&self) {} }
struct Y;
impl Bar for Y { fn bar(&self) {} }
struct Z;
impl Bar for Z { fn bar(&self) {} }
let mut x: Box<dyn Bar> = Box::new(X /* or Y or Z */);
x.bar();
Run Code Online (Sandbox Code Playgroud)
然而,这伴随着友好调度的Box开销dyn。您拥有的代码是更好的解决方案。如果您愿意,可以使用enum_dispatch板条箱移除一些样板:
#[enum_dispatch]
trait Bar { fn bar(&self); }
#[enum_dispatch(Bar)]
enum Foo {
A(X),
B(Y),
C(Z),
}
let foo = Foo::A(X);
foo.bar();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2030 次 |
| 最近记录: |