【问题标题】:Is it possible to somehow cast Vec<Option<Value>> into Vec<Value> after filtering out None elements in Rust? [duplicate]在过滤掉 Rust 中的 None 元素后,是否可以以某种方式将 Vec<Option<Value>> 转换为 Vec<Value> ? [复制]
【发布时间】:2019-06-28 14:17:23
【问题描述】:

在编写这样的代码时,我想要某种方式来进行这样的转换:

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()
}

我怎样才能做到这一点?我认为类型暗示机制不够聪明,无法确定生成的集合将仅包含 Option&lt;Value&gt;,其中所有此类对象的类型都相同 (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>`

【问题讨论】:

    标签: functional-programming rust iterator


    【解决方案1】:

    您可以使用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();
    

    Playground

    【讨论】:

    • 感谢大家的回答并指出类似的问题!很高兴成为这样一个响应迅速且聪明的社区的一员!
    • 我发现flatten().collect() 可以做到这一点,我感到非常惊喜。 Rust 太棒了!
    • 是的。 flatten 更好。我总是忘记Option 也实现了Iterator
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2020-01-09
    相关资源
    最近更新 更多