在数组中查找具有最大属性的项
问题描述:
我有一个这样的结构
struct Point {
pub x: i32,
pub y: i32,
}
impl Point {
fn new(x: i32, y: i32) -> Self {
Point { x, y }
}
}
还有这样的数组
[Point::new(1, 1), Point::new(4, 2), Point::new(2, 9)];
如何从该数组中提取具有最大 point.x
的项目?
How do I pull the item with largest point.x
from this array?
答
let a = [Point::new(1, 1), Point::new(4, 2), Point::new(2, 9)];
let max = a.iter().max_by_key(|p| p.x);
另见: