October 2026
Intermediate to advanced
748 pages
18h 51m
English
Save the environment! Create a closure today!
Cormac Flanagan
Sorting a vector of integers is easy:
integers.sort();
It is, therefore, a sad fact that when we want some data sorted, it’s hardly ever a vector of integers. We typically have records of some kind, and the built-in sort method typically does not work:
structCity{name:String,population:i64,country:String,...}fnsort_cities(cities:&mutVec<City>){cities.sort();// error: how do you want them sorted?}
Rust complains that City does not implement std::cmp::Ord. We need to specify the sort order, like this:
/// Helper function for sorting cities by latitude.fncity_latitude(city:&City)->i64{city.latitude}fnsort_cities(cities:&mutVec<City>){cities.sort_by_key(city_latitude);// ok}
The helper function, city_latitude, takes a City record and extracts the key, the field by which we want to sort our data. The sort_by_key method takes this key-function as a parameter.
Read now
Unlock full access