Reputation: 1085
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
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