Rust 闭包

对整型向量进行排序很容易:

integers.sort();

遗憾的是,当我们想对一些数据进行排序时,它们几乎从来都不是整型向量。例如,对某种记录型数据来说,内置的 sort 方法一般不适用:

struct City {
    name: String,
    population: i64,
    country: String,
    ...
}

fn sort_cities(cities: &mut Vec<City>) {
    cities.sort();  // 出错:你到底想怎么排序?
}

使用该例子即可正常

struct Car {
    money: i32,
}

impl std::ops::Add for Car {
    type Output = i32;

    fn add(self, other: Car) -> i32 {
        self.money + other.money
    }
}

impl Drop for Car {
    fn drop(&mut self) {
        println!("Car {} is dropped", self.money);
    }
}

fn main() {
    let car1 = Car { money: 3000 };
    let car2 = Car { money: 2000 };
    let mut cars = vec![car1, car2];
    cars.sort_by_key(|car| car.money);
    for x in cars {
        println!("{}", x.money);
    };
}