[英]How do I pass in a trait object to a vector that will also have a uniform type in the vector of the vector?
[英]How do I create a new vector of Trait from vectors of types that implement Trait?
我想创建一个包含实现Trait
对象的新向量,从我已经拥有的包含这些对象的一些向量。
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());
如果可能的话,我怎么能实现这个目标?
好吧,如果你有一个Bar
,并且你需要一个Box<Foo>
,那么你需要首先打包该值,然后将其转换为一个特征对象,如下所示:
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>));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.