Implement Add and AddAssign so that p1 + p2 and p += q work for Point
Point is a 2D point with integer coordinates. Make p1 + p2 return a new point with the summed coordinates, and make p += q add q to p in place.
Constraints:
- Use the operator traits from
std::ops; do not add inherent methods such asplus. +returns aPoint;+=changes the left operand and returns nothing.- Do not change the struct or
main.
use std::ops::{Add, AddAssign};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
// your code here: impl Add and impl AddAssign for Point
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 10, y: 20 };
let mut p = p1 + p2;
println!("{p:?}"); // Point { x: 11, y: 22 }
p += Point { x: 1, y: 1 };
println!("{p:?}"); // Point { x: 12, y: 23 }
}Write the implementation.
Implement std::ops::Add with type Output = Point; and fn add(self, other: Point) -> Point summing the fields, then AddAssign with fn add_assign(&mut self, other: Point). Output is what + returns; += is its own trait.
- Expecting
impl Addto make+=work too, thoughAddAssignis a separate trait - Leaving out
type Output, which everyAddimplementation must declare - Looking for
#[derive(Add)]in the standard library, which has none
- What would
p1 + p2do top1ifPointwere notCopy? - How would you make both
p * 2and2 * pcompile forPoint?
The compiler rewrites a + b as a call to Add::add(a, b), and a += b as AddAssign::add_assign(&mut a, b). These are two different traits: implementing Add does not give +=, and without AddAssign the line p += … fails to compile with error E0368.
use std::ops::{Add, AddAssign};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl AddAssign for Point {
fn add_assign(&mut self, other: Point) {
self.x += other.x;
self.y += other.y;
}
}
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 10, y: 20 };
let mut p = p1 + p2;
println!("{p:?}"); // Point { x: 11, y: 22 }
p += Point { x: 1, y: 1 };
println!("{p:?}"); // Point { x: 12, y: 23 }
}type Output is an associated type: it says what + returns for this pair of operands. It is usually Self, but it does not have to be: in the standard library Instant - Instant returns a Duration. The right operand is set by the parameter Rhs, which defaults to Self, so impl Add for Point means Point + Point. add takes self by value; for Point this goes unnoticed because it is Copy, and p1 stays usable after the addition. A non-Copy type would be moved by a + b — then the trait is also implemented for references, impl Add for &Point. add_assign takes &mut self and returns nothing: it changes the left operand in place.