rust - 如何从实现该特征的结构迭代器中收集特征向量
问题描述
我正在尝试从实现该特征的结构迭代器中获取特征向量。
到目前为止,我能够做到这一点:
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());
}
推荐阅读
- c# - 如何在 RDLC 报告向导 c# Windows 应用程序中添加动态超链接
- jquery - Jquery validate 不能在 bootstrap-tokenfield 上工作
- jwt - quarkus 是否支持 gzip jwt 令牌
- graphql - 列出 NestJS + GraphQL 中的所有查询和突变名称
- node.js - 如何在nodejs中使while循环与switch case同步?
- asp.net - 包括 CSS 和 JavaScript 作为 Web 表单用户控件并使其尽可能快
- javascript - 如何在laravel中使用对象数据数组进行ajax发布
- google-bigquery - 我在哪里可以在我的 BigQuery 中找到广告系列级否定关键字(从 Google Ads 传输数据后)?
- javascript - 使用 render_template 在 Flask 中未正确显示阿姆哈拉语字体
- swift - 为什么 500/1000 打印的是 0?