Sum of array of structs

I have the following definition:

struct A {
a : u8
}

impl Add for A
{
fn add(self, rhs : A) -> Self
{
return A{self.a + rhs.a};
}
}

fn main() -> ()
{
let arr : [A; 3] = [a, a2, a3];
let a : A = arr.iter().sum();
}

How can I get this work?

Please have a read through this post to see how to format code so others can read it:


What errors are you seeing? Please include them in your post and then re-read the error message so you know why the compiler is complaining.

I'd suggest removing the whole impl Add for A and reading the compile error you get from the let a: A = arr.iter().sum() line to see which traits are needed to make some_iterator.sum() work (hint: maybe Add isn't what you want).

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.