如何从实现 Trait 的类型向量创建新的 Trait 向量? [英] How do I create a new vector of Trait from vectors of types that implement Trait?

查看:27
本文介绍了如何从实现 Trait 的类型向量创建新的 Trait 向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含实现 Trait 的对象的新向量,从我已经拥有的一些包含这些对象的向量中.

I would like to create a new vector that contains objects that implement Trait, from some vectors I already have which contain those objects.

trait Foo {
    //
}


struct Bar {
    i: i32,
}


struct Baz {
    c: char,
}

impl Foo for Bar {
    //
}

impl Foo for Baz {
    //
}
fn main() {
    let v1 = vec![Bar{i: 2},Bar{i: 4}];
    let v2 = vec![Baz{c: '2'},Baz{c: '4'}];

    let mut v_all: Vec<Box<Foo>> = Vec::new();

    v_all.extend(v1.into_iter());
    v_all.extend(v2.into_iter());

}

这当然让我着迷

<anon>:34:11: 34:33 error: type mismatch resolving `<collections::vec::IntoIter<Bar> as core::iter::Iterator>::Item == Box<Foo>`: expected struct Bar, found box
<anon>:34     v_all.extend(v1.into_iter());

如果可能,我怎样才能做到这一点?

How could I achieve this, if possible?

推荐答案

好吧,如果你有一个 Bar,并且你需要一个 Box,那么你需要先将值装箱,然后将其转换为 trait 对象,如下所示:

Well, if you have a Bar, and you need a Box<Foo>, then you need to first box the value, then cast it to a trait object, which looks like this:

v_all.extend(v1.into_iter().map(|e| Box::new(e) as Box<Foo>));
v_all.extend(v2.into_iter().map(|e| Box::new(e) as Box<Foo>));

这篇关于如何从实现 Trait 的类型向量创建新的 Trait 向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆