仅使用非 None 值初始化 Vec

at5*_*321 5 rust

如果我有这样的变量:

let a: u32 = ...;
let b: Option<u32> = ...;
let c: u32 = ...;
Run Code Online (Sandbox Code Playgroud)

,制作这些值的向量的最短方法是什么,以便仅在 b 为 时才包含 b Some

换句话说,有没有比这更简单的事情:

let v = match b {
    None => vec![a, c],
    Some(x) => vec![a, x, c],
};
Run Code Online (Sandbox Code Playgroud)

PS 我更喜欢一个不需要多次使用变量的解决方案。考虑这个例子:

let some_person: String = ...;
let best_man: Option<String> = ...;
let a_third_person: &str = ...; 
let another_opt: Option<String> = ...;
...
Run Code Online (Sandbox Code Playgroud)

可以看出,我们可能必须使用更长的变量名、多个Option( None)、表达式(如a_third_person.to_string())等。

Cha*_*man 2

你的很好,但这是一个复杂的:

[Some(a), b, Some(c)].into_iter().flatten().collect::<Vec<_>>()
Run Code Online (Sandbox Code Playgroud)

这自OptionimplsIntoIterator起就有效。