Reputation: 17
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
Reputation: 9617
Two possibilities:
Ord
trait for your struct and use the sort
/sort_unstable
methodssort_by_key
/sort_unstable_by_key
methodsYou'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