作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个如下的枚举:
enum Foo {
A(X),
B(Y),
C(Z),
}
其中 X、Y 和 Z 是实现方法 bar()
的结构
我希望能够在 Foo
枚举上定义一个方法 bar
,以便它调用其内部值的相应方法。现在我有这个:
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 和动态调度的开销。您拥有的代码是更好的解决方案。您可以使用 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();
关于Rust - 调用内部值方法的枚举方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69669984/
我是一名优秀的程序员,十分优秀!