January 2022
Intermediate to advanced
680 pages
11h 35m
Japanese
環境を救おう(セーブしよう)! クロージャを作ろう!
−Cormac Flanagan†1
[†1] 訳注:米国のコンピュータ科学者。https://users.soe.ucsc.edu/~cormac/
整数のベクタをソートするのは簡単だ。
integers.sort();
ただ悲しいことに、何かをソートしたいと思ったときに、それが整数のベクタであることはほとんどない。大抵の場合、ソートしたいのは何らかのレコードで、組み込みのsortメソッドではソートできない。
struct City {
name: String,
population: i64,
country: String,
...
}
fn sort_cities(cities: &mut Vec<City>) {
cities.sort(); // error: how do you want them sorted?
エラー: どうソートしたらいいかわからない
エラーが起きたのは、Cityがstd::cmp::Ordを実装していないからだ。次のようにソートの順番を指定してやればよい。
都市を人口でソートするための補助関数
/// Helper function for sorting cities by population.
fn city_population_descending(city: &City) -> i64 {
-city.population
}
fn sort_cities(cities: &mut Vec<City>) {
cities.sort_by_key(city_population_descending); // ok
}
この補助関数city_population_descending ...
Read now
Unlock full access