Rust OR between two options

Aur*_*ult 0 operators rust

I want to know if its possible to perform an OR operation between two Options. Something like :

let a = Some(3);
let b = None;
let result = a || b;
Run Code Online (Sandbox Code Playgroud)

Here I want the result variable to have either the value of a if it's a Some or the value of b.

I didn't find any documentation of this on Internet.

Öme*_*den 7

在 Rust 中,逻辑 OR ( ||) 的操作数 必须是bool. 所以不可能将它与Option或任何其他类型一起使用。

但是,请参阅or从方法文档Option

如果它包含一个值,则返回选项,否则返回 optb。

你的问题可以这样解决:

let a = Some(3);
let b = None;
let result = a.or(b); // result: Some(3)
Run Code Online (Sandbox Code Playgroud)

如果你想要结果,bool你可以使用is_someis_none

let result = a.or(b).is_some(); // true
let result = None.or(None).is_some(); // false
Run Code Online (Sandbox Code Playgroud)

要不然

传递给或急切评估的参数;如果传递函数调用的结果,建议使用 or_else,它是惰性求值的。

您也可以or_else在这样的情况下使用:

let a = Some(3);
let result = a.or(produce_option());
Run Code Online (Sandbox Code Playgroud)

正如您从代码中看到的,无论您a是运行Some还是None运行produce_option,这在某些(或许多)情况下可能效率不高。

let result = a.or_else(produce_option);
Run Code Online (Sandbox Code Playgroud)

在这里produce_option的时候才会被称为aNone


对于逻辑与&&),您可以使用and 方法Option

let a = None;
let b = Some(4);
let result = a.and(b); // result: None
Run Code Online (Sandbox Code Playgroud)

对于懒惰的评估,您可以使用AND_THEN 之类的OR_ELSE


UNWRAP_OR

unwrap_orunwrap_or_else如果您想在比较时获取选项中的值,或者也可以使用。但这要视情况而定,我以这个为例:

let a = None;
let b = None;
let x:i32 = a.unwrap_or(b.unwrap_or_default()); //Since `i32`'s default value is 0 `x` will be equal to 0

let a = None;
let b = Some(3);
let x:i32 = a.unwrap_or_else(||b.unwrap_or_default()); // `x` will be eqaul to 3
//using `unwrap_or_else` might be a better idea, because of the lazy evaluation.
Run Code Online (Sandbox Code Playgroud)

注意:此答案侧重于Option但这些都适用于Result具有相同错误类型的对象。