'More Succinct Option Comparison
Supposing I have two option-wrapped variables, is there a better way to compare them than this?
fn comp(a: Option<i32>, b: Option<i32>) -> bool {
match a {
Some(ai) => match b {
Some(bi) => ai == bi,
_ => false,
},
None => match b {
None => true,
_ => false,
}
}
}
I don't want to lose the case where they might both be None and therefore equal, but this seems like a lot of matching for a relatively simple thing. I'm also trying to avoid unwrap().
Solution 1:[1]
Options can be compared directly, so you can simply return a == b.
Solution 2:[2]
Actually, if T: PartialEq, Option<T>: PartialEq and if T: Eq, Option<T>: Eq. See this example (Playground):
fn main() {
assert_eq!(Some(3), Some(3));
assert_ne!(Some(3), None);
assert_eq!(None, None);
assert_ne!(Some(3), Some(4));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ForceBru |
| Solution 2 | E_net4 - Krabbe mit Hüten |
