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

Collect vector of borrowed values into vec of borrowed trait

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

这是一个基于 Vector of objects belonging to 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());
    }
}

这失败了 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);

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

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

有关详细信息,请参阅 this playground