I have a struct like this
struct Point {
pub x: i32,
pub y: i32,
}
impl Point {
fn new(x: i32, y: i32) -> Self {
Point { x, y }
}
}
And an array like this
[Point::new(1, 1), Point::new(4, 2), Point::new(2, 9)];
How do I pull the item with largest point.x
from this array?
Use 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);
There's also Iterator::min_by_key
.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With