【问题标题】:Collect vector of borrowed values into vec of borrowed trait将借用值的向量收集到借用特征的向量中
【发布时间】:2021-10-26 01:02:01
【问题描述】:

是否可以从实现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&lt;&amp;dyn Animal&gt;" 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);

【问题讨论】:

    标签: rust polymorphism idioms


    【解决方案1】:

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

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

    请参阅this playground 了解更多信息。

    【讨论】:

    • 而且由于您在 v 的类型中指定了 trait,您也可以使用 .map(|a| a as _) 并让编译器发挥它的魔力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 2014-05-11
    相关资源
    最近更新 更多