Aurélien Foucault
Aurélien Foucault

Reputation: 559

Rust OR between two options

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;

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.

Upvotes: 1

Views: 2093

Answers (1)

Ömer Erden
Ömer Erden

Reputation: 8813

In Rust operands of Logical OR (||) must be bool. So it is not possible to use it with Option or any other type.

But please see the or method from the documentation of Option.

Returns the option if it contains a value, otherwise returns optb.

Your problem can be solved like this:

let a = Some(3);
let b = None;
let result = a.or(b); // result: Some(3)

If you want result as a bool you can use is_some or is_none

let result = a.or(b).is_some(); // true
let result = None.or(None).is_some(); // false

OR_ELSE

Arguments passed to or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use or_else, which is lazily evaluated.

You can also use or_else in a situation like this :

let a = Some(3);
let result = a.or(produce_option());

As you can see from the code whether your a is Some or None it will run produce_option, this may not be efficient in some(or many) circumstances.

let result = a.or_else(produce_option);

In here produce_option will only be called when a is None


AND

For Logical AND (&&) you can use and method of Option.

let a = None;
let b = Some(4);
let result = a.and(b); // result: None

For a lazy evaluation you can use AND_THEN like OR_ELSE.


UNWRAP_OR

unwrap_or or unwrap_or_else is also usable if you want to take the value inside the options while comparing. But this depends on the case, i am writing this as an example:

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.

Note : This answer focused on Option but these are all applicable for Result objects which have same error type.

Upvotes: 10

Related Questions