Sum of struct using a function

I am having difficulty writing a function which calculates sum of two variables in a struct named Point. The point struct looks like below :

struct Point {
pub x: u8,
pub y: u8,
}

I tried the following but it didn't work :
pub fn sum_points(points: &[&Point]) -> Point {
points.iter().sum()
}

I am very new to Rust language (started using today).

The sum() method on iterators is powered by the std::iter::Sum trait and you'll need to tell the compiler how to calculate the "sum" of a iterator/stream of Points.

One possible implementation would be to use a loop and a temporary variable.

use std::iter::Sum;

impl Sum for Point {
   pub fn sum<I>(iter: I) -> Self
    where
        I: Iterator<Item = A>
  {
    let mut total = Point { x: 0, y: 0 };

    for point in iter {
        total.x += point.x;
        total.y += point.y;    
    }

    total
  }
}

It is also possible to write your own behaviour for the + operator by implementing std::ops::Add for your type.

That seems working but one thing more : If I want the variables x and y in struct Point to be of type u:8 but their sum output to be of type u:16. How would I do that ? I tried the following :

impl Point {

fn sum(&self)->u16 {

    let sum_of_point:u16 =  (self.x as u16)+(self.y as u16);

    return sum_of_point

}

}

But I think its not going to work. I have to satisfy the following assertions in my program :

let p : Point;

assert_eq!(type_of(&p.x), type_name::<u8>());
assert_eq!(type_of(&p.y), type_name::<u8>());
assert_eq!(p.sum(), (p.x + p.y) as u16);

You might want to share your code examples in a playground link (using the share button on that website) so that we can better see what exactly you’re trying to do and what kind of errors you’re getting in your attempt to get it to work. If you’re posting rust code here, you should wrap it in three backticks, e.g.

```
fn some_rust_code() {
    // ...
}
```

becomes

fn some_rust_code() {
    // ...
}

The sum function seems to work correctly. Using assert_eq to check types isn’t the most sensible thing to do, at least the way you did it for p.x and p.y.

Here’s some example test case that succeeds: Rust Playground

Thank you so much. It finally worked. And satisfied the asserts too :slight_smile:

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.