在具有最大属性的数组中查找项

ca1*_*1ek 3 rust

我有这样的结构

struct Point {
    pub x: i32,
    pub y: i32,
}

impl Point {
    fn new(x: i32, y: i32) -> Self {
        Point { x, y }
    }
}
Run Code Online (Sandbox Code Playgroud)

还有像这样的数组

[Point::new(1, 1), Point::new(4, 2), Point::new(2, 9)];
Run Code Online (Sandbox Code Playgroud)

如何point.x从此阵列中拉出最大的项目?

She*_*ter 7

用途Iterator::max_by_key:

let a = [Point::new(1, 1), Point::new(4, 2), Point::new(2, 9)];
let max = a.iter().max_by_key(|p| p.x);
Run Code Online (Sandbox Code Playgroud)

还有Iterator::min_by_key.