Nathaniel Ford
Nathaniel Ford

Reputation: 21239

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().

Upvotes: 0

Views: 431

Answers (2)

jthulhu
jthulhu

Reputation: 8678

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));
}

Upvotes: 3

ForceBru
ForceBru

Reputation: 44888

Options can be compared directly, so you can simply return a == b.

Upvotes: 5

Related Questions