我正在尝试从实现该特征的结构迭代器中获取特征向量。
到目前为止,我能够做到这一点:
fn foo() -> Vec<Box<dyn SomeTrait>> {
let v: Vec<_> = vec![1]
.iter()
.map(|i| {
let b: Box<dyn SomeTrait> = Box::new(TraitImpl { id: *i });
b
})
.collect();
v
}
但是,我想使其更加简洁。
最佳答案
这对我有用。 Playground
尽管我不是Rust专家,所以我不确定'static
中foo<S: SomeTrait + 'static>
的限制
trait SomeTrait { fn echo(&self); }
impl SomeTrait for u32 {
fn echo(&self) {
println!("{}", self);
}
}
fn foo<S: SomeTrait + 'static>(iter: impl Iterator<Item=S>) -> Vec<Box<dyn SomeTrait>> {
iter.map(|e| Box::new(e) as Box<dyn SomeTrait>).collect()
}
fn main() {
let v = vec!(1_u32, 2, 3);
let sv = foo(v.into_iter());
sv.iter().for_each(|e| e.echo());
}
关于rust - 如何从实现该特征的结构迭代器中收集特征向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63088520/