How to sort a vector containing structs?

Viewed 557

Lets say I have some code like:

struct GenericStruct {
    a: u8,
    b: String,
}

fn sort_array(generic_vector: Vec<GenericStruct>) -> Vec<GenericStruct> {
    // Some code here to sort a vector.
    todo!();
}

fn main() {
    let some_words = String::from("Hello Word");
    let x = GenericStruct { a: 25, b: some_words };
    let some_vector: Vec<GenericStruct> = vec![x];
}

How could I sort vectors based on one part of it, such as sorting by "a", or sorting by the length of "b"?

1 Answers

Two possiblities.

Either implement the Ord trait for your struct, or use the sort_unstable_by_key method.

You'd use the former if, for your generic_struct, there is an obvious and single way to sort them that makes sense not just in your current sorting use case but generally.

You'd use the latter if this sorting scheme is more of a "one off".

somevector.sort_unstable_by_key(|element| element.a)
Related