Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the item in an array with the largest property

Tags:

rust

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?

like image 351
ca1ek Avatar asked Mar 14 '16 21:03

ca1ek


Video Answer


1 Answers

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:

  • How can min_by_key or max_by_key be used with references to a value created during iteration?
  • Using max_by_key on a vector of floats
  • What is the idiomatic way to get the index of a maximum or minimum floating point value in a slice or Vec in Rust?
like image 191
Shepmaster Avatar answered Oct 25 '22 15:10

Shepmaster