Sub topic 8
Implementing operators for references
This chapter assumes you know how to implement Add for a type, how the Output associated type works, and why operators take their operands by value.
The problem with by-value operators
a + b calls Add::add(a, b), and both operands are moved into the call. For a Copy type such as a two-field f64 vector, that costs nothing. For a type that owns heap data, such as a Vec, the move consumes both operands. You would have to write a.clone() + b.clone() to keep using them, and each clone allocates.
The fix is to implement the operator trait for references to your type. Then &a + &b borrows both operands and leaves them usable.
Implementing Add for &Series
Series wraps a Vec<f64>, so it cannot be Copy. The reference impl does the real work. The by-value impl forwards to it.
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);
}Three details matter here.
Add<&Series> for &Seriesnames the trait'sRhsparameter explicitly. HereSelfis&SeriesandRhsis&Series. The anonymous lifetimes are filled in by the compiler.OutputisSeries, an owned value. The result is new data, so it cannot borrow from the operands.- The by-value impl delegates.
&self + &rhsborrows the two owned values, calls the reference impl, and then drops them. The arithmetic lives in one place.
After the let c = &a + &b; line, a and b are still valid. After let d = a + b; they are moved.
Which combinations to provide
The compiler treats Series + Series, &Series + &Series, Series + &Series and &Series + Series as four separate impls. Std does the same for its numeric types. For your own types, a practical rule is:
| Impl | When to write it |
|---|---|
| `&T + &T` | Always, for non-`Copy` types. This is the core impl. |
| `T + T` | Always. Forward to the reference impl. |
| `T + &T`, `&T + T` | Only if callers ask for them. Each is one more impl to maintain. |
If a type is Copy, by-value impls alone are enough, because a + b does not consume a or b.
Using reference operators in generic code
A function bounded by T: Add<Output = T> consumes its operands. To write a generic function that adds borrowed values, bound the reference type instead. This needs a higher-ranked trait bound, because the reference lifetime is not known to the caller.
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())
}
}
fn add_refs<T>(a: &T, b: &T) -> T
where
for<'a> &'a T: Add<&'a T, Output = T>,
{
a + b
}
fn main() {
let a = Series(vec![1.0]);
let b = Series(vec![2.0]);
assert_eq!(add_refs(&a, &b), Series(vec![3.0]));
assert_eq!(add_refs(&1, &2), 3);
}for<'a> &'a T: Add<&'a T, Output = T> reads as "for every lifetime 'a, a reference to T can be added to another reference to T, producing a T." The integer call works because std implements Add<&i32> for &i32.
Exercise
You have a non-Copy type Matrix and you implement only Add for Matrix. A caller writes let s = &m1 + &m2;. What happens, and what is the smallest fix?
Show answer
It fails to compile, because no impl of Add<&Matrix> exists for &Matrix. Add impl Add<&Matrix> for &Matrix with type Output = Matrix, and have impl Add for Matrix call &self + &rhs.