在过滤掉 Rust 中的 None 元素后,是否有可能以某种方式将 Vec<Option<Value>> 转换为 Vec<Value> ?

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)

操场

  • 我发现“flatten().collect()”可以解决问题,我感到非常惊讶。《铁锈》太棒了! (4认同)
  • 是的。“展平”甚至更好。我总是忘记`Option`也实现了`Iterator` (3认同)