Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Both are rather ugly. This is much more idiomatic:

    match (x, y) {
        (Some(x), Some(y)) => Some(x + y),
        _ => None,
    }


Don’t know Rust, but wouldn’t this have to be:

    (Some(x), Some(y)) => Some(x + y)
    else => None


You're correct, except that "else" is a keyword and so cannot be used there. You'd want

  _ => None,
instead, which is the "catch all" arm.

(For those that didn't catch it, the parent code is trying to use None, but it's actually a tuple, and there's four different cases here, not two. So the catch-all arm is better than spelling each of them out in this case.)


You're right – fixed. That's what I get from writing code in a simple text area.


Your "fixed" version is also broken (at time of writing). :-)


Fixed again. I'm starting to run out of excuses... ;-)


This has been a thing since Rust 1.0. Just use the beautiful properties of match (or the "later" `if let`, of course). I prefer this and wish I could say it was idiomatic, but some tools like clippy push users over to helper methods instead of simple applications of match.


Pretty sure clippy will tell you to rewrite it as:

    if let (Some(x), Some(y)) = (x, y) {
       Some(x + y)
    } else {
       None
    }
`match` in place of `if` looks weird. IMO example with `zip` is better though.


Clippy will not complain about the parent's code. It's not really in place of an if; there's four cases there. To be honest, I find 'if let... else None' to be worse looking than the match, though I'm unsure if I truly prefer the zip version to the Some(x? + y?) version.


    Some(x? + y?)




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: