Sub topic 6
Compound Assignment with AddAssign and Friends
This chapter assumes you know structs, traits, associated types, and the difference between moving and copying a value. It also assumes you have read the earlier chapters on Add and the Output type.
What `+=` really calls
The expression a += b does not expand to a = a + b. It calls a different trait method, AddAssign::add_assign(&mut a, b). Every arithmetic and bitwise operator has a matching compound trait in std::ops.
| Expression | Trait | Method |
|---|---|---|
| `a += b` | `AddAssign` | `add_assign` |
| `a -= b` | `SubAssign` | `sub_assign` |
| `a *= b` | `MulAssign` | `mul_assign` |
| `a /= b` | `DivAssign` | `div_assign` |
| `a %= b` | `RemAssign` | `rem_assign` |
The compound traits differ from Add in two ways. The method takes &mut self, so it changes the left operand in place. It also returns (), so the trait has no Output type.
Implementing AddAssign
The left operand is borrowed mutably, so it is not moved. The right operand is still passed by value. This example also implements Neg, which the unary operators chapter covers.
use std::ops::{AddAssign, Neg};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl AddAssign for Vec2 {
fn add_assign(&mut self, rhs: Vec2) {
self.x += rhs.x;
self.y += rhs.y;
}
}
impl Neg for Vec2 {
type Output = Vec2;
fn neg(self) -> Vec2 {
Vec2 { x: -self.x, y: -self.y }
}
}
fn main() {
let mut p = Vec2 { x: 1.0, y: 1.0 };
p += Vec2 { x: 2.0, y: 3.0 };
assert_eq!(p, Vec2 { x: 3.0, y: 4.0 });
assert_eq!(-p, Vec2 { x: -3.0, y: -4.0 });
}The binding p must be declared mut. Without it, the compiler rejects p += ... because the call needs &mut p.
Why a separate trait?
Compound assignment lets a type update itself without building a new value. For a type that owns heap data, such as a large Vec or a String, this can avoid an allocation. String works this way: s += "text" appends to the existing buffer.
The two traits are independent. Implementing Add does not give you AddAssign, and the reverse is also true. If you want both operators, implement both. A common pattern is to write the in-place version first and build the by-value version on it:
use std::ops::{Add, AddAssign};
#[derive(Debug, Clone, PartialEq)]
struct Series(Vec<f64>);
impl AddAssign<&Series> for Series {
fn add_assign(&mut self, rhs: &Series) {
for (a, b) in self.0.iter_mut().zip(&rhs.0) {
*a += *b;
}
}
}
impl Add<&Series> for Series {
type Output = Series;
fn add(mut self, rhs: &Series) -> Series {
self += rhs;
self
}
}
fn main() {
let mut a = Series(vec![1.0, 2.0]);
let b = Series(vec![3.0, 4.0]);
a += &b;
assert_eq!(a, Series(vec![4.0, 6.0]));
let c = a + &b;
assert_eq!(c, Series(vec![7.0, 10.0]));
}Here add takes self by value, so it reuses the left operand's buffer. No new Vec is allocated.
Common errors
- Forgetting
mut. The variable on the left of+=must be mutable. - Expecting
+=to useAdd. If onlyAddis implemented,a += bfails with "binary assignment operation+=cannot be applied". ImplementAddAssigntoo. - Using
+=through a shared reference. Givenr: &Vec2,*r += xfails. You need&mut Vec2. - Mismatched right-hand types.
AddAssign<&Series>acceptsa += &b, but nota += b. The type parameter decides which form works.
Exercise
A type implements Add and Copy but not AddAssign. Does let mut p = q; p += q; compile? What is the smallest change that fixes it?
Show answer
It does not compile, because += requires AddAssign and Add does not provide it. Add impl AddAssign for T with fn add_assign(&mut self, rhs: T) { *self = *self + rhs; }. This works because T is Copy, so *self can be read without moving out of the borrow.
Exercise
Why does add_assign have no Output associated type?
Show answer
It modifies the left operand through &mut self and returns (), so there is no new value whose type needs to be named.