Enum的值如何作为类型
這位寫C++的老兄想寫以前的Enum
fn pet(_: Animal::Whale) {}
fn pet(_: Animal::Dog) {}
// or somehow describe a trait that forces its implementors to impl specific enum variants; not allow them to impl the whole enum
trait Petter<T> {
fn pet(_: Animal::T);
}
rust的近似方案1
struct Dog {}
struct Whale {}
enum Animal {
Dog(Dog),
Whale(Whale),
}
rust的近似方案2
// given there is a trait Bar, and types A and B implement it:
enum Foo {
A(A),
B(B),
}
impl Bar for Foo {
fn bar(&self) {
match self {
A(a) => a.bar(),
B(b) => b.bar(),
}
}
}
impl From<A> for Foo {
fn from(a: A) -> Foo {
Foo::A(a)
}
}
有個庫enum_dispatch可以達到類似的效果
#[enum_dispatc