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

标签 rust polymorphism idioms

是否可以收集 Vec<&dyn Trait>来自实现 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 &狗`

但是,如果您将狗单独插入 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了解更多信息。

关于rust - 将借用值的向量收集到借用特征的 vec 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68930532/

相关文章:

rust - 如何定义闭包类型以发送到线程安全

rust - 从另一个模块打印 vec 中的值 : field of struct is private

rust - 为什么我不能使用返回编译时常量的函数作为常量?

python - 多态性的实际例子

r - 根据键在数据框中汇总值

generics - 具有特征的通用函数,用于读取提示错误特征的数字

c++ - 当基类指针指向在基类中声明的派生类虚函数时,为什么会出现编译时错误?

haskell - 用于在两种类型之间转换的多态函数

c - 重新学习 C : New idioms?

python - 一行 'if'/'for' -statements 是好的 Python 风格吗?