Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort an array of optional values in Rust?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading