1

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"?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

5

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)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
cadolphs
  • 9,014
  • 1
  • 24
  • 41
  • 1
    note the `sort_by_key` will also work, it has the advantage of being stable but is slower unless your data consists mostly of sorted runs. – Aiden4 Oct 07 '21 at 02:42