gpt4 book ai didi

Rust - 调用内部值方法的枚举方法

转载 作者:行者123 更新时间:2023-12-03 08:15:04 24 4
gpt4 key购买 nike

我有一个如下的枚举:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com