[英]How can I collect a vector of Traits from an iterator of structs implementing that trait
我正在嘗試從實現該特征的結構迭代器中獲取特征向量。
到目前為止,我能夠做到這一點:
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
}
但我想讓它更簡潔。
這對我有用。 操場
雖然我不是 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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.