Sub topic 4
Operands are moved: Copy and ownership
This chapter assumes you know Rust ownership and moves, the Copy trait, and the basic impl Add for T pattern from the previous chapters.
Operators take their operands by value
The expression a + b is sugar for Add::add(a, b). The trait method has this signature:
fn add(self, rhs: Rhs) -> Self::OutputBoth self and rhs are taken by value. The operator therefore follows the normal ownership rules. If the operand type is not Copy, the operator moves it, and the original variable can't be used afterwards.
Copy types: the move is invisible
For a Copy type, passing by value copies the bits, so both variables stay usable. This is why Vec2 derives Copy.
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 }
}
}
fn main() {
let a = Vec2 { x: 1.0, y: 2.0 };
let b = Vec2 { x: 3.0, y: 4.0 };
let sum = a + b;
// a and b were copied, so they are still valid here.
assert_eq!(sum, Vec2 { x: 4.0, y: 6.0 });
assert_eq!(a + b, sum);
}Small, plain-data types such as points, complex numbers, and fixed-size vectors are good candidates for Copy. A type can only derive Copy if all its fields are Copy.
Non-Copy types: operands are consumed
A type that owns heap data, such as a Vec, can't be Copy. Adding two of them with a by-value impl moves both.
use std::ops::Add;
#[derive(Debug, Clone, PartialEq)]
struct Series(Vec<f64>);
impl Add 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 main() {
let a = Series(vec![1.0, 2.0]);
let b = Series(vec![3.0, 4.0]);
let c = a.clone() + b.clone();
assert_eq!(c, Series(vec![4.0, 6.0]));
// The last use can move the originals.
let d = a + b;
assert_eq!(d, c);
}If you wrote let c = a + b; and then used a again, the compiler would reject it with error[E0382]: borrow of moved value: a. The fix shown above is to clone the operands. That costs an allocation and a copy for each clone.
Why by-value can be an advantage
Taking self by value lets an implementation reuse the left operand's memory instead of allocating a new buffer.
use std::ops::Add;
#[derive(Debug, PartialEq)]
struct Series(Vec<f64>);
impl Add<&Series> for Series {
type Output = Series;
fn add(mut self, rhs: &Series) -> Series {
for (a, b) in self.0.iter_mut().zip(&rhs.0) {
*a += b;
}
self
}
}
fn main() {
let a = Series(vec![1.0, 2.0]);
let b = Series(vec![3.0, 4.0]);
let c = a + &b; // a is consumed and reused; b is only borrowed
assert_eq!(c, Series(vec![4.0, 6.0]));
assert_eq!(b, Series(vec![3.0, 4.0]));
}Here Rhs is &Series, so the right operand is borrowed and stays valid. The left operand is consumed, and its Vec becomes the result with no new allocation. The next chapters cover the Rhs parameter and reference impls in detail.
Choosing between the options
| Situation | Typical choice |
|---|---|
| Small plain-data type | Derive `Copy` and implement the operator by value |
| Large or heap-owning type, callers want to keep operands | Implement the operator for `&T` |
| Left operand is a throwaway buffer | By-value `self`, reusing its memory |
Exercise
Given struct Matrix(Vec<f64>) with only impl Add for Matrix, why does let c = m1 + m2; println!("{:?}", m1); fail to compile, and what are two ways to fix it?
Show answer
Add::add takes self by value, and Matrix is not Copy, so m1 is moved into the call and can't be used afterwards. Two fixes: clone the operand (m1.clone() + m2), or implement Add for &Matrix and write &m1 + &m2 so the operands are only borrowed.