Is there a way to implement the Sum
trait for non-std types? I’ve been searching for an answer and have yet to come across anything on how it might be done or if it is possible. I will start with the type I would like to sum, how I’ve implemented it now, and then how I would like to implement it to start.
I have this Point
the type I would like to sum.
pub struct Point {
x: f64,
y: f64,
}
And this is how I am currently summing it. The behaviour I would like is for the x
and y
from each Point
to be added together.
pub fn sum_points(points: &[&Point]) -> Point {
Point {
x: points.iter().map(|point| point.x).sum(),
y: points.iter().map(|point| point.y).sum(),
}
}
I would like to be able to write it like this.
pub fn sum_points(points: &[&Point]) -> Point {
points.iter().sum()
}
But as I said I have not been able to find a way to do this yet. I have read enough to have been able to implement a subtraction.
use std::ops::Sub;
impl Sub for &Point {
type Output = Point;
fn sub(self, other: &Point) -> Point {
Point {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
But when I have tried to do similar things (copying from the Rust source code) I have not quite been able to get it to work.
std::iter::Sum;
impl Sum for Point {
fn sum(iter: Iterator<Item = Point>) -> Point {
iter.fold(Point { x: 0.0, y: 0.0 }, |a, b| Point {
x: a.x + b.x,
y: a.y + b.y,
})
}
}
impl<'a> Sum<&'a Point> for Point {
fn sum(iter: Iterator<Item = &'a Point>) -> Point {
iter.fold(Point { x: 0.0, y: 0.0 }, |a, b| Point {
x: a.x + b.x,
y: a.y + b.y,
})
}
}
I am hoping someone can point me in the right direction to get this to work. Even if it is not currently possible it would be nice just to know why.
pub fn sum_points(points: &[&Point]) -> Point {
points.iter().sum()
}
Thanks!