Reputation: 1552
How to modify if let
statement so it also handles another condition like Some(7) == b
?
let a = Some(6);
let b = Some(7);
if let Some(6) = a /* && Some(7) = b */{
// do something
}
Upvotes: 52
Views: 31105
Reputation: 43
You can use zip function over Option type.
let a = Some(10);
let b = Some(5);
if let Some((x @ 10, y @ 5)) = a.zip(b) {
// a and b is Some and has specified values.
} else {
// a or b or both is none, or one of the values is not matched
}
Docs: https://doc.rust-lang.org/std/option/enum.Option.html#method.zip
Upvotes: 1
Reputation: 29972
The if let
expression only admits one match arm pattern against one expression. However, they can be merged together into a single equivalent pattern match condition. In this case, the two Option
values can be combined into a pair and matched accordingly.
if let (Some(6), Some(7)) = (a, b) {
// do something
}
See also:
Upvotes: 23
Reputation: 69276
You can use a simple tuple:
if let (Some(6), Some(7)) = (a, b) {
// do something
}
Upvotes: 91