Sub topic 4
Operands are moved: Copy and ownership
This chapter assumes you know Rust ownership and borrowing, the Copy and Clone traits, generics with trait bounds, and the basic impl Add for T shape from the previous chapters. Here you will see how operator expressions interact with moves, why a + b can make a unusable, and which design options you have when it does.
Operators take their operands by value
The Add trait declares its method like this:
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Both self and rhs are taken by value. The expression a + b is sugar for Add::add(a, b), so it follows the same ownership rules as any function call. Each operand is evaluated, left first and then right, and then passed into add.
- If the operand's type implements
Copy, the call copies it. The original variable stays valid. - If the type does not implement
Copy, the call moves it. The original variable is unusable afterwards.
Nothing about operators changes this. Rust does not insert a borrow for you, so a + b never turns into &a + &b. Method calls like a.len() auto-borrow their receiver. Operators do not.
The Copy case: nothing to think about
A small numeric struct is the easy case. Every field is Copy, so you can derive Copy and Clone for the struct.
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 c = a + b;
// a and b were copied into the call, so both are still usable.
assert_eq!(c, Vec2 { x: 4.0, y: 6.0 });
assert_eq!(a + a, Vec2 { x: 2.0, y: 4.0 });
assert_eq!(b, Vec2 { x: 3.0, y: 4.0 });
}The expression a + a is legal only because Vec2 is Copy. Writing the same thing with a non-Copy type fails, as the next section shows.
The non-Copy case: the left operand is gone
A type that owns heap memory cannot be Copy. Deriving Copy on a struct that holds a Vec is a compile error, because Vec<f64> is not Copy. Consider a Series type that wraps a Vec<f64>.
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]));
let d = a + b;
assert_eq!(c, d);
// println!("{:?}", a);
// error[E0382]: borrow of moved value: `a`
}The call a + b moves both values into add. When add returns, they are dropped, so the later println! would not compile. The .clone() calls on the first addition keep a and b alive, at the cost of allocating two new vectors that are thrown away immediately.
This is the central tension of this chapter. Operator syntax makes it look cheap and harmless to use a value twice, but ownership still applies.
Why by-value is not always a cost
Taking self by value sounds like a limitation, but it can be a performance feature. If add owns its left operand, it can reuse that operand's allocation instead of building a new one.
use std::ops::Add;
#[derive(Debug, Clone, PartialEq)]
struct Series(Vec<f64>);
impl Add 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, 3.0]);
let b = Series(vec![10.0, 20.0, 30.0]);
let c = Series(vec![100.0, 200.0, 300.0]);
// Chained additions reuse a's buffer each time. No new Vec is allocated.
let total = a + b + c;
assert_eq!(total, Series(vec![111.0, 222.0, 333.0]));
}Because a + b + c parses as (a + b) + c, the temporary from the first addition is moved into the second. That temporary is the same buffer as a. A chain of by-value additions therefore does no extra allocation. This is the standard library's own approach: String + &str takes the String by value, appends to its buffer, and returns it.
The trade-off is that the caller loses the left operand. If both operands must stay usable, you need another design.
Choosing a strategy
When callers want to keep their operands, you have three options.
| Strategy | Caller writes | Cost | When to choose it |
|---|---|---|---|
| Derive `Copy` | `a + b` | A bitwise copy per use | Small, plain-data types such as points, complex numbers, and fixed-size vectors |
| Clone at the call site | `a.clone() + b.clone()` | A heap allocation per clone | Rarely. Fine in prototypes or non-hot code |
| Implement the operator for references | `&a + &b` | One allocation for the result only | Types that own heap data and are often reused |
The third option gets its own chapter, so only the shape is shown here: you write impl Add<&Series> for &Series, and the caller's operands are borrowed rather than moved. For now, remember that implementing the operator for references is the idiomatic answer when Copy is not available.
The decision flow looks like this:
What Copy requires, and what it costs
A few rules decide whether you can derive Copy:
- Every field must be
Copy. AString,Vec, orBoxfield rules it out. CopyrequiresClone, so you always derive both together:#[derive(Clone, Copy)].- A type that implements
Dropcannot beCopy. The compiler rejects the combination. Copyis a promise that duplicating the value by memcpy is correct. A type whose copies would share some identity, such as a unique handle or token, should not beCopyeven if the compiler would allow it.
Size matters too. A copy happens on every use, so a Copy type that is very large, such as a 16x16 matrix of f64 at 2 KiB, copies 2 KiB on every +. The optimizer often removes these copies when add is inlined, but you should not count on it for large types. For big fixed-size types, implementing the operators on references is often better even though Copy is available.
Generic code feels this too
The move rule leaks into generic functions. A bound like T: Add<Output = T> says only that T can be added by value. It says nothing about whether you can use a value twice.
use std::ops::Add;
fn double<T>(x: T) -> T
where
T: Add<Output = T> + Copy,
{
x + x
}
fn main() {
assert_eq!(double(21), 42);
assert_eq!(double(1.5), 3.0);
}Remove Copy from the bound and the compiler reports use of moved value: x. The error is correct. x + x needs two owned copies of x, and the bound only promises one. You then have two choices: require Copy, or require Clone and write x.clone() + x. The bound you pick decides which types your function accepts. Copy is cheaper and reads well for numbers. Clone accepts more types, but hides allocations inside generic code.
Moves in larger expressions
A single expression can move the same variable twice. The compiler rejects this for non-Copy types:
use std::ops::Add;
#[derive(Debug, Clone, PartialEq)]
struct Series(Vec<f64>);
impl Add 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 sum = a.clone() + b.clone();
let doubled = a.clone() + a;
assert_eq!(sum, Series(vec![4.0, 6.0]));
assert_eq!(doubled, Series(vec![2.0, 4.0]));
}In a.clone() + a, the left side evaluates first and borrows a only for the clone. The right side then moves a. The code compiles because the borrow ends before the move. Writing a + a.clone() fails, because the left operand has already moved a by the time the right side runs.
Common errors
use of moved valueafter an addition. The operand type is notCopy. Clone it, add&a + &bimpls, or restructure so each value is used once.the trait Copy cannot be implemented for this type. A field is notCopy. Change the field type, or give upCopyand implement operators for references.Tcannot be used twice in a generic function. Add aCopyorClonebound that matches what the function needs.- Overusing
.clone()to silence the compiler. In a loop, this allocates on every iteration. Switch to reference impls or compound assignment, which the next chapters cover.
Exercise
Why does let c = a + b; println!("{:?}", a); compile when a is a Vec2 that derives Copy, but fail when a is a Series wrapping a Vec<f64>?
Show answer
a + b calls Add::add(a, b), which takes a by value. For a Copy type the call copies a, so the variable is still valid. Series is not Copy, so the call moves a into add, and using it afterwards is error E0382. Fixes are cloning first, implementing Add for &Series, or using each value only once.
Exercise
A generic function fn square<T: Mul<Output = T>>(x: T) -> T { x * x } fails to compile. Why, and what are two ways to fix it?
Show answer
x * x uses x twice, but Mul::mul takes both operands by value, so the first use moves x. Fix it by adding Copy to the bound (T: Mul<Output = T> + Copy), or by adding Clone and writing x.clone() * x. The Copy bound is cheaper but accepts fewer types.