gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:36:44 24 4
gpt4 key购买 nike

是否可以收集 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com