Sub topic 6
Compound Assignment with AddAssign and Friends
This chapter assumes you know how to implement Add for a struct, what the Output associated type does, and how Copy, moves and &mut borrows work. It builds on the earlier chapters on Add, Output and operand ownership.
How `+=` maps to a trait
Every arithmetic and bitwise operator has a compound assignment form, and each form has its own trait in std::ops. When the operands are not primitive numbers, the expression a += b becomes a call to AddAssign::add_assign(&mut a, b).
| Operator | Trait | Method | Column |
|---|---|---|---|
| `+=` | `AddAssign` | `add_assign` | |
| `-=` | `SubAssign` | `sub_assign` | |
| `*=` | `MulAssign` | `mul_assign` | |
| `/=` | `DivAssign` | `div_assign` | |
| `%=` | `RemAssign` | `rem_assign` | |
| `&=` | `BitAndAssign` | `bitand_assign` | |
| `\ | =` | `BitOrAssign` | `bitor_assign` |
| `^=` | `BitXorAssign` | `bitxor_assign` | |
| `<<=` | `ShlAssign` | `shl_assign` | |
| `>>=` | `ShrAssign` | `shr_assign` |
Differences from `Add`
The signature of AddAssign shows how it differs from Add:
pub trait AddAssign<Rhs = Self> {
fn add_assign(&mut self, rhs: Rhs);
}- The method takes
&mut selfinstead ofself, so the left operand is borrowed, not consumed. - It returns
(). There is noOutputtype, because the result is stored in the left operand. Rhsdefaults toSelf, as it does forAdd. You can set it to another type for mixed operands.- The traits are independent. Implementing
Adddoes not give you+=, and implementingAddAssigndoes not give you+.
A first implementation
This example implements three compound traits for a Copy type. MulAssign<f64> uses a different Rhs type.
use std::ops::{AddAssign, MulAssign, SubAssign};
#[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 SubAssign for Vec2 {
fn sub_assign(&mut self, rhs: Vec2) {
self.x -= rhs.x;
self.y -= rhs.y;
}
}
impl MulAssign<f64> for Vec2 {
fn mul_assign(&mut self, k: f64) {
self.x *= k;
self.y *= k;
}
}
fn nudge(p: &mut Vec2, d: Vec2) {
*p += d;
}
fn main() {
let mut p = Vec2 { x: 1.0, y: 1.0 };
p += Vec2 { x: 2.0, y: 3.0 };
p -= Vec2 { x: 1.0, y: 1.0 };
p *= 2.0;
assert_eq!(p, Vec2 { x: 4.0, y: 6.0 });
nudge(&mut p, Vec2 { x: 1.0, y: 1.0 });
assert_eq!(p, Vec2 { x: 5.0, y: 7.0 });
}The body of add_assign uses += on f64 fields. For primitive types the compiler handles += directly, so there is no recursion into your trait.
What the left operand must be
The left side of += must be a place expression that you are allowed to mutate: a mut variable, a field of one, a dereferenced &mut, or an indexed element when IndexMut is implemented. A value such as the result of a function call does not qualify.
In nudge above, the parameter p has type &mut Vec2. Writing p += d fails, because &mut Vec2 does not implement AddAssign. You must dereference with *p += d.
Relating `Add` and `AddAssign`
Most types should support both a + b and a += b, and the two should give the same result. You write the logic once and implement the other trait on top of it. Which direction to delegate depends on whether the type is Copy.
- Copy types. Implement
Addfirst, then write*self = *self + rhs;insideadd_assign. Copying is cheap, so nothing is lost. - Types that own heap data. Implement
AddAssignfirst, then buildAddon it.Addtakesselfby value, so it can mutate that value and return it. This reuses the left operand's allocation instead of creating a new one.
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) {
assert_eq!(self.0.len(), rhs.0.len(), "Series length mismatch");
for (a, b) in self.0.iter_mut().zip(&rhs.0) {
*a += *b;
}
}
}
impl AddAssign for Series {
fn add_assign(&mut self, rhs: Series) {
*self += &rhs;
}
}
impl Add<&Series> for Series {
type Output = Series;
fn add(mut self, rhs: &Series) -> Series {
self += rhs;
self
}
}
fn main() {
let mut total = Series(vec![0.0, 0.0]);
let a = Series(vec![1.0, 2.0]);
let b = Series(vec![3.0, 4.0]);
total += &a;
total += &b;
assert_eq!(total, Series(vec![4.0, 6.0]));
let sum = a + &b;
assert_eq!(sum, total);
}This code makes three choices:
AddAssign<&Series>is the primary implementation. It allocates nothing and writes into the existing buffer.- The by-value
AddAssignforwards to the reference version. The caller gives uprhsand its buffer is dropped afterwards. - The length check is explicit. Without it,
zipwould stop at the shorter side and silently leave the tail ofselfunchanged. Choose a policy (panic, truncate, or return aResultfrom a named method) and document it.
Rhs types and inference
A type may implement a compound trait several times with different Rhs types. Each implementation is a separate impl of a generic trait, so they do not conflict. A Vec2 could have MulAssign<f64> and MulAssign<f32>.
This can cause inference trouble. With only MulAssign<f64>, the literal in v *= 2.0 is inferred as f64. With several float impls, the literal's type may be ambiguous and you must write 2.0_f64. Add overloads only when callers need them.
Evaluation order for primitives
For overloaded operators, the left operand is evaluated first, then the right. For primitive operand types, the compiler evaluates the right operand first, then the place on the left. The difference only shows when both sides have side effects, but it is one reason to keep operand expressions simple.
Using the traits in generic code
A compound assignment bound lets generic code accumulate in place:
use std::ops::AddAssign;
fn sum_all<T>(items: &[T]) -> T
where
T: Copy + Default + AddAssign,
{
let mut acc = T::default();
for &x in items {
acc += x;
}
acc
}
fn main() {
assert_eq!(sum_all(&[1, 2, 3]), 6);
assert_eq!(sum_all(&[0.5, 1.5]), 2.0);
}Here T: AddAssign means AddAssign<T>, because Rhs defaults to Self. If T is not Copy, change the loop to for x in items and bound T: for<'a> AddAssign<&'a T>.
Design guidelines
- Make
a += bmean the same thing asa = a + b. Callers will assume it does. - Implement compound traits for types where in-place update is natural: numeric types, vectors, matrices, sets, bit flags, and accumulators.
- Do not give
+=an unrelated meaning, such as appending to a log, just because the syntax is short. A named method is clearer. - If an operation can fail, such as a length mismatch, an operator cannot return a
Result. Document the panic, or provide a separatetry_add_assignmethod. - For indexed targets,
grid[(1, 2)] += 5already works onceIndexMutis implemented and the element type supports+=. You do not need a separate impl.
Exercise
A learner writes let total = Series(vec![0.0]); total += &a; and the compiler rejects it, even though AddAssign<&Series> is implemented. What is wrong, and what is the fix?
Show answer
add_assign takes &mut self, so the left operand must be a mutable place. total is not declared mut, so the borrow fails. Declare it as let mut total = ....
Exercise
You have a Copy type Meters(f64) that already implements Add<Output = Meters>. Write the body of add_assign for it without touching the inner field directly, and explain why the same approach is a poor choice for Series.
Show answer
Use *self = *self + rhs;. For a Copy type the copies cost almost nothing. For Series, *self + rhs would consume a clone of self and allocate a new Vec, and the old buffer would be dropped when it was overwritten. Implementing AddAssign directly on the existing buffer, and building Add on top of it, avoids that allocation.