仅从选项向量中获取“Some”内部的惯用方法?

rtv*_*iii 5 iteration vector rust

我正在学习 Rust,并试图习惯使用Results 和Options。给定一个向量。如果我只想要没有错误的结果(或者没有错误的结果Option),是否有比下面更优雅的方法,或者这与我通常需要编写的样板数量有关?

我意识到人们可以做更多的事情来获得map好的结果unwrap_or_elsepartition不是坏的结果。


    let optvec   = vec![Some(1), None, Some(4), None];
    let filtered = optvec.iter()
    .filter(|q| q.is_some())
    .map(|q| q.unwrap())
    .collect::<Vec<i32>>();

Run Code Online (Sandbox Code Playgroud)

nlt*_*lta 11

您可以使用filter_map它仅返回 Somes 而不是 Nones。

let optvec   = vec![Some(1), None, Some(4), None];
let filtered: Vec<i32> = optvec.iter().filter_map(|f| *f).collect();
println!("{:?}", filtered);
>>> [1, 4]
Run Code Online (Sandbox Code Playgroud)

  • 你也可以只使用`.flatten()`,因为`Option&lt;T&gt;`也实现了`Iterator&lt;Item=T&gt;` (4认同)