将借用值的向量收集到借用特征的 vec 中

Flo*_*rit 3 polymorphism idioms rust

是否可以Vec<&dyn Trait>从实现的值的迭代器中收集 a Trait

这是一个示例,基于属于特征问题的对象向量

trait Animal {
    fn make_sound(&self) -> String;
}

struct Dog;
impl Animal for Dog {
    fn make_sound(&self) -> String {
        "woof".to_string()
    }
}

fn main() {
    let dogs = [Dog, Dog];
    let v: Vec<&dyn Animal> = dogs.iter().collect();

    for animal in v.iter() {
        println!("{}", animal.make_sound());
    }
}
Run Code Online (Sandbox Code Playgroud)

这与error[E0277]: a value of type "Vec<&dyn Animal>" cannot be built from an iterator over elements of type &Dog`失败

但是,如果您使用将狗单独推入 vec(如原始问题的答案中),则它可以正常工作。

let dog1: Dog = Dog;
let dog2: Dog = Dog;

let v: Vec<&dyn Animal> = Vec::new();
v.push(&dog1);
v.push(&dog2);
Run Code Online (Sandbox Code Playgroud)

Flo*_*rit 6

为了将结构的 Iterator 收集到由 Struct 实现的特征的 Vector 中,可以使用map迭代器的方法将借用的结构转换为借用的特征。

let dogs = [Dog, Dog];
let v: Vec<&dyn Animal> = dogs.iter().map(|a| a as &dyn Animal ).collect();
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此游乐场

  • 因为你在 `v` 类型中指定了 trait,你也可以做 `.map(|a| a as _)` 并让编译器发挥它的魔力。 (2认同)