Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to choose the first Some() Option?

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.

like image 359
ilmoi Avatar asked Jun 04 '21 08:06

ilmoi


Video Answer


1 Answers

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

like image 176
Denys Séguret Avatar answered Oct 18 '22 17:10

Denys Séguret