enum_dispatch在rust中的简单使用
请先看下面这个例子: enum Creatures { Dog(Dog), Cat(Cat), } trait Animal { fn make_sound(&self); } struct Dog; struct Cat; impl Animal for Dog { fn make_sound(&self) { println!("Bark!"); } } impl Animal for Cat { fn make_sound(&self) { println!("Meow!"); } } fn main() { let animals: Vec<Creatures> = vec![ Creatures::Dog(Dog), Creatures::Cat(Cat), ]; for animal in animals { match animal { Creatures::Dog(dog) => dog.make_sound(), Creatures::Cat(cat) => cat.make_sound(), } } } 在 main 函数中,我们创建了一个名为 animals 的 Vec<Creatures> 向量,其中包含不同种类的生物。遍历 animals 向量时,使用 match 语句来确定每个生物的实际类型,然后调用相应实例的 make_sound 方法。...