我有一个如下的枚举:
enum Foo {
A(X),
B(Y),
C(Z),
}
其中 X、Y 和 Z 是实现该方法的结构体bar()
我希望能够定义一个方法bar
on the Foo
enum 以便调用其内部值对应的方法。现在我有这个:
impl Foo {
pub fn bar() {
match self {
Foo::A(f) => { f.bar(); }
Foo::B(f) => { f.bar(); }
Foo::C(f) => { f.bar(); }
}
}
}
如果可能的话,如何使用枚举做得更好?
您可以使用特征对象,而不是使用枚举:
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();
然而,这会带来开销Box
and dyn
友好派遣。您拥有的代码是更好的解决方案。您可以使用enum_dispatch https://docs.rs/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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)