Slim Shady
Slim Shady

Reputation: 1085

How can you get the sum of all keys in an array of structs?

I have this struct:

struct MyStruct {
    myvalue: u32,
    yourvalue: u32,
}

If I have a: Vec<MyStruct> how can I get the sum of all MyStruct.myvalue? I'm looking for something like a.iter.sum(sum of myvalue).

I know I can do it with a for loop, but I would like to be able to do this with one line of code.

Upvotes: 5

Views: 2616

Answers (1)

Shepmaster
Shepmaster

Reputation: 432139

To sum MyStruct.myvalue in a single line you can use Iterator::map and Iterator::sum.

fn sum_myvalue(a: &[MyStruct]) -> u32 {
    a.iter().map(|s| s.myvalue).sum()
}

// Later on you can use this like so:
//
sum_myvalue(a);

See also:

Upvotes: 10

Related Questions