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 None
s (and not compare the values of Some
s), you can use sort[_unstable]_by_key(|v| v.is_some())
. Since false
compares before true
, this will place the None
s first.