是否有可能以某种方式投VEC >成VEC 鲁斯特滤除无元件后? [重复]

问题描述 投票:1回答:1

我想这样的编写代码时某种方式有这样的转换:

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<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>`
functional-programming rust iterator
1个回答
3
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.