-
Notifications
You must be signed in to change notification settings - Fork 13.7k
Add Option::merge
under option_merge
feature gate
#84695
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
This patch adds unstable `Option::merge` method which takes two `Option<T>`s and a `T -> T -> T` function. If only one of the options is `Some(_)` the method returns it. If both options are `None` the method returns `None`. Otherwise, if both options are `Some(_)` the method merges them by applying the given function.
r? @yaahc (rust-highfive has picked a reviewer for you, use r? to override) |
coalesce has a different meaning in SQL, I don't think that's a great choice:
|
You can write this today by treating both options as iterators and using fn f(x: Option<u32>, y: Option<u32>) -> Option<u32> {
x.into_iter().chain(y.into_iter()).min()
}
fn main() {
assert_eq!(f(None, None), None);
assert_eq!(f(Some(10), None), Some(10));
assert_eq!(f(None, Some(5)), Some(5));
assert_eq!(f(Some(10), Some(5)), Some(5));
} However, that's certainly not the most convenient approach. Another option, which is reasonably clear: If we consider adding this function, I'd suggest calling it |
Some potential example usage of this method can be found here: https://doc.rust-lang.org/src/core/iter/adapters/zip.rs.html#162 |
r? @m-ou-se |
Thanks for your PR. I'm not convinced we should add this, though. I can't think of a lot of use cases that aren't already covered by Pinging @rust-lang/libs in case anyone feels like this would be an important addition. Otherwise I'll close this PR. |
I've wanted this function a few times, but I don't know if it's sufficiently common to justify a function in std. |
Triage: There's no comment to support this strongly since @m-ou-se left a comment, so I'm going to close. Thanks! |
I've made a micro crate that provides the function, in case anyone needs it too: |
tl;dr: add the following method to
Option<T>
underoption_merge
feature gate:The method returns
Some(f(l, r))
if both options areSome(_)
Some(x)
if either of the options isSome(x)
and the other isNone
None
if both options areNone
It is very similar to
Option::zip_with
(orOption::zip
+Option::map
) with the difference that it doesn't returnNone
if only one of the inputs isNone
This can be very handy when, for example, calculating a minimum of two options (without inflicting with
None
).Some usage examples:
I'm not sure about the name, some other ideas:
coalesce
combine
reduce
(suggested in AddOption::merge
underoption_merge
feature gate #84695 (comment))