Sub topic 8
Implementing Operators for References
This chapter assumes you can write impl Add for T, know what the Output associated type is, and understand moves and Copy. It covers what to do when the operand type is expensive to move or clone.
Why references need their own impls
An operator takes its operands by value. a + b is Add::add(a, b), so for a type that is not Copy, the expression moves both a and b. After that line, neither variable is usable.
Cloning before every addition avoids the move, but it allocates. The fix is to implement the operator for references as well. Then &a + &b borrows both operands and builds only the result.
use std::ops::Add;
#[derive(Debug, Clone, PartialEq)]
struct Series(Vec<f64>);
impl Add<&Series> for &Series {
type Output = Series;
fn add(self, rhs: &Series) -> Series {
Series(self.0.iter().zip(&rhs.0).map(|(a, b)| a + b).collect())
}
}
impl Add for Series {
type Output = Series;
fn add(self, rhs: Series) -> Series {
&self + &rhs
}
}
fn main() {
let a = Series(vec![1.0, 2.0]);
let b = Series(vec![3.0, 4.0]);
let c = &a + &b;
assert_eq!(c, Series(vec![4.0, 6.0]));
let d = a + b;
assert_eq!(d, c);
}In impl Add<&Series> for &Series, the reference is the Self type. The trait is implemented for &Series, which is a different type from Series. The by-value impl delegates to the reference impl, so the arithmetic is written once.
Inside the closure, a and b are &f64. The standard library implements Add for &f64 + &f64, so no dereferencing is needed.
The four combinations
Rust does not borrow or dereference operands automatically for operators. Each combination of owned and borrowed operands is a separate impl.
| Expression | Impl needed |
|---|---|
| `a + b` | `Add<Series> for Series` |
| `a + &b` | `Add<&Series> for Series` |
| `&a + b` | `Add<Series> for &Series` |
| `&a + &b` | `Add<&Series> for &Series` |
The standard library does this for every integer and float type. i32 has all four impls, which is why &x + &y works on references from iter().
If you implement only some combinations, the others fail to compile:
error[E0277]: cannot add `&Series` to `Series`The error means no Add<&Series> for Series impl exists. Operators never insert & for you.
Forwarding the impls
You can forward all four impls to the reference impl. You can also let an owned operand's allocation be reused. When the left operand is owned, add can modify it in place and return it. That avoids a second allocation.
use std::ops::Add;
#[derive(Debug, Clone, PartialEq)]
struct Series(Vec<f64>);
impl Add<&Series> for &Series {
type Output = Series;
fn add(self, rhs: &Series) -> Series {
Series(self.0.iter().zip(&rhs.0).map(|(a, b)| a + b).collect())
}
}
impl Add<&Series> for Series {
type Output = Series;
fn add(mut self, rhs: &Series) -> Series {
self.0.truncate(rhs.0.len());
for (a, b) in self.0.iter_mut().zip(&rhs.0) {
*a += b;
}
self
}
}
impl Add<Series> for &Series {
type Output = Series;
fn add(self, rhs: Series) -> Series {
rhs + self
}
}
impl Add for Series {
type Output = Series;
fn add(self, rhs: Series) -> Series {
self + &rhs
}
}
fn main() {
let a = Series(vec![1.0, 2.0]);
let b = Series(vec![3.0, 4.0]);
let expected = Series(vec![4.0, 6.0]);
assert_eq!(&a + &b, expected);
assert_eq!(a.clone() + &b, expected);
assert_eq!(&a + b.clone(), expected);
assert_eq!(a + b, expected);
}The diagram shows where each impl sends its work.
rhs + self in the third impl relies on addition being commutative. That is true for element-wise f64 addition. For a non-commutative operator, such as matrix multiplication or subtraction, you cannot swap the operands. Write that impl out or route it through the reference impl.
Lifetimes in the impl header
impl Add<&Series> for &Series uses elided lifetimes. The compiler treats it as impl<'a, 'b> Add<&'b Series> for &'a Series. The two operands may have unrelated lifetimes, which is what you want.
Output is Series, which owns its data, so no lifetime appears in it. You would write explicit lifetimes only if the output borrowed from an operand.
References for Copy types
A Copy type does not need reference impls to avoid moves, because a + b copies. References still matter for generic code and for iterators. slice.iter() yields &T, and &T + &T does not compile unless the impl exists. For Copy types, forward to the by-value impl:
use std::ops::Add;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl Add for Vec2 {
type Output = Vec2;
fn add(self, rhs: Vec2) -> Vec2 {
Vec2 { x: self.x + rhs.x, y: self.y + rhs.y }
}
}
impl Add<&Vec2> for &Vec2 {
type Output = Vec2;
fn add(self, rhs: &Vec2) -> Vec2 {
*self + *rhs
}
}
fn main() {
let pts = [Vec2 { x: 1.0, y: 1.0 }, Vec2 { x: 2.0, y: 3.0 }];
assert_eq!(&pts[0] + &pts[1], Vec2 { x: 3.0, y: 4.0 });
}Using reference impls in generic code
To require that &T + &T works for a generic T, you need a bound on the reference type. The reference's lifetime is not fixed by the caller, so the bound must hold for every lifetime. That is a higher-ranked trait bound, written for<'a>:
use std::ops::Add;
fn sum_all<T>(items: &[T]) -> Option<T>
where
T: Clone,
for<'a> &'a T: Add<&'a T, Output = T>,
{
let mut iter = items.iter();
let first = iter.next()?.clone();
Some(iter.fold(first, |acc, x| &acc + x))
}
fn main() {
assert_eq!(sum_all(&[1, 2, 3]), Some(6));
assert_eq!(sum_all(&[0.5, 1.5]), Some(2.0));
assert_eq!(sum_all::<i32>(&[]), None);
}Only the first element is cloned. Every later step borrows the accumulator and the next item. The Series type from earlier satisfies this bound, because it has Clone and &Series + &Series with Output = Series.
Exercise
A type Series has impl Add for Series and impl Add<&Series> for &Series. Why does a + &b fail to compile, and what is the smallest fix?
Show answer
Operators do not auto-borrow or auto-dereference. a + &b needs an impl whose Self is Series and whose Rhs is &Series, and neither existing impl matches. Add impl Add<&Series> for Series. It can forward with &self + rhs, or modify self in place for efficiency.