11

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ca1ek
  • 405
  • 1
  • 4
  • 14

1 Answers1

12

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366