If I have a number of Option<T>'s and I want to pick the first one that is Some rather than None - is there an idiomatic way to do that?
My naive approach:
pub fn pick_first_option_available<T>(a: Option<T>, b: Option<T>, c: Option<T>) -> Option<T> {
    match a {
        Some(a) => Some(a),
        None => match b {
            Some(b) => Some(b),
            None => match c {
                Some(c) => Some(c),
                None => None,
            },
        },
    }
}
One obvious issue with the above is that it's limited to a fixed number of Options (3). I would prefer to have a more general function.
There is a somewhat related thread here, but it tackles summing instead of picking options.
Yes, there's a simple and idiomatic way:
a.or(b).or(c)
You don't usually define a function just for this.
Option#or
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With