user13149230
user13149230

Reputation: 17

How to sort a vector of structs?

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 a portion, such as sorting by a or sorting by the length of b?

Upvotes: 1

Views: 2209

Answers (1)

cadolphs
cadolphs

Reputation: 9617

Two possibilities:

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)

Upvotes: 5

Related Questions