Home > Software design >  How to sort an array of optional values?
How to sort an array of optional values?

Time:08-26

I have an array of optional values

struct Foo;

let array: [Option<Foo>; 5] = [
    Some(Foo {}), 
    Some(Foo {}), 
    None, 
    Some(Foo {}), 
    None
]; 

How to sort the array to "bubble" all None values to the top (left/ascending)?

The expected result should look like this

println!("{:?}", array) // [None, None, Some(Foo {}), Some(Foo {}), Some(Foo {})]

CodePudding user response:

None is compared as less than Some, so assuming Foo implements Ord, you just need to call sort_unstable() (or sort() for stable sorting).

If you only want to bubble Nones (and not compare the values of Somes), you can use sort[_unstable]_by_key(|v| v.is_some()). Since false compares before true, this will place the Nones first.

  • Related