3 ms·
Both are rather ugly. This is much more idiomatic: match (x, y) { (Some(x), Some(y)) => Some(x + y), _ => None, }
by adwn 4y ago
Both are rather ugly. This is much more idiomatic:
match (x, y) {
(Some(x), Some(y)) => Some(x + y),
_ => None,
}
- kzrdude 4y agoThis 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.
- dullcrisp 4y agoDon’t know Rust, but wouldn’t this have to be: (Some(x), Some(y)) => Some(x + y) else => None
- deleted 4y ago[deleted]
- steveklabnik 4y agoYou'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.)
- adwn 4y agoYou're right – fixed. That's what I get from writing code in a simple text area.
- deleted 4y ago[deleted]
- 0x457 4y agoPretty 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.
- steveklabnik 4y agoClippy 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.
- stouset 4y agoSome(x? + y?)