【问题标题】:How can I convert a Vec<Option<T>> to an Option<Vec<T>>如何将 Vec<Option<T>> 转换为 Option<Vec<T>>
【发布时间】:2019-02-20 01:04:55
【问题描述】:

我有一些这样的向量

let example1: Vec<Option<u64>> = vec![None, None, Some(2), Some(35)];
let example2: Vec<Option<u64>> = vec![Some(5), Some(19), Some(4), Some(6)];

我想要一个函数,它会为example1 返回None,但会为example2 返回Some([5, 19, 4, 6])

换句话说,如果任何选项为None,我想要一个返回None 的函数,但如果所有选项都是Some,它会将它们全部解包并返回Some

【问题讨论】:

    标签: rust


    【解决方案1】:

    将其转换为迭代器并使用.collect::&lt;Option&lt;Vec&lt;_&gt;&gt;&gt;()

    let output = vec.into_iter().collect::<Option<Vec<_>>>();
    

    或使用类型注释

    let output: Option<Vec<_>> = vec.into_iter().collect();
    

    参见collect() 和它用于Options 的FromIterator trait implentation

    【讨论】:

    • 请注意,Result 也有一个实现。
    猜你喜欢
    • 1970-01-01
    • 2018-08-27
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多