Vla*_*yev 4 iterator functional-programming rust
在编写这样的代码时,我想要某种方式来进行这样的转换:
struct Value;
fn remove_missed(uncertain_vector: Vec<Option<Value>>) -> Vec<Value> {
uncertain_vector
.into_iter()
.filter(|element| match element {
Some(val) => true,
None => false,
})
.collect()
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?我相信类型隐含机制不够聪明,无法确定生成的集合将仅包含Option<Value>
所有此类对象的类型相同的地方 ( Value
)。
编译器部分回答了我的问题:
error[E0277]: a collection of type `std::vec::Vec<Value>` cannot be built from an iterator over elements of type `std::option::Option<Value>`
--> src/lib.rs:10:10
|
10 | .collect()
| ^^^^^^^ a collection of type `std::vec::Vec<Value>` cannot be built from `std::iter::Iterator<Item=std::option::Option<Value>>`
|
= help: the trait `std::iter::FromIterator<std::option::Option<Value>>` is not implemented for `std::vec::Vec<Value>`
Run Code Online (Sandbox Code Playgroud)
bel*_*lst 13
您可以使用Iterator::filter_map
一次性过滤和映射元素。
let v = vec![None, None, Some(1), Some(2), None, Some(3)];
let filtered: Vec<_> = v.into_iter().filter_map(|e| e).collect();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1771 次 |
最近记录: |