Sub topic 9
Using Copy and Clone as generic bounds
This chapter assumes you know Rust generics and trait bounds, and that you understand moves, Copy, and Clone from the earlier chapters. It shows how to choose between T: Copy and T: Clone when you write generic functions.
Why bounds matter
Inside a generic function, the compiler knows nothing about T except what its bounds say. If T has no bounds, assigning a value of type T may move it, and the compiler assumes the worst. Adding Copy or Clone tells the compiler which duplication operations are legal.
| Bound | What it allows | Cost to the caller |
|---|---|---|
| `T: Copy` | Implicit duplication with `=`, reading through `&T` by value (`*r`) | Only cheap, bitwise types qualify |
| `T: Clone` | Explicit `.clone()` calls | Accepts `String`, `Vec`, `Rc`, and `Copy` types too |
| neither | Only moves and borrows | Accepts every type |
Every Copy type is also Clone, because Copy requires Clone as a supertrait. So T: Clone accepts a strictly larger set of types than T: Copy.
A function that needs Copy
The function below returns the largest item in a slice. It receives &[T], which only lends the items, so it cannot move them out. The Copy bound lets it return an owned T by value.
fn largest<T: PartialOrd + Copy>(items: &[T]) -> Option<T> {
let mut iter = items.iter().copied();
let mut max = iter.next()?;
for x in iter {
if x > max {
max = x;
}
}
Some(max)
}
fn main() {
println!("{:?}", largest(&[3, 9, 4]));
println!("{:?}", largest::<f64>(&[]));
}This prints Some(9) and then None. The copied() adapter turns an iterator of &T into an iterator of T, and it exists only when T: Copy. Without the bound, the compiler reports that it cannot move out of a borrowed slice element.
Relaxing the bound to Clone
Copy is restrictive: largest would reject a slice of String. If you can accept an explicit duplication, use Clone instead.
fn largest_cloned<T: PartialOrd + Clone>(items: &[T]) -> Option<T> {
let mut iter = items.iter();
let mut max = iter.next()?;
for x in iter {
if x > max {
max = x;
}
}
Some(max.clone())
}
fn main() {
let words = vec![String::from("pear"), String::from("zebra"), String::from("apple")];
println!("{:?}", largest_cloned(&words));
println!("{:?}", largest_cloned(&[3, 9, 4]));
}This version compares references while scanning and clones only once, at the end. It prints Some("zebra") and then Some(9). Cloning once instead of on every comparison is a good habit: a Clone bound signals that the function may allocate.
Choosing the bound
Ask these questions in order:
- Can the function work with references only? Then use no bound and return
&T. This is the most general signature. - Does it need an owned value, and is it reasonable to ask for a clone? Use
T: Clone. - Is the function a hot path over small numeric-like values, where a hidden allocation would be a bug? Use
T: Copy. The bound documents and enforces that the call is cheap.
flowchart TD
A[Does the function need an owned T?] -->|No| B[Take &T, no bound]
A -->|Yes| C[Must duplication be cheap and implicit?]
C -->|Yes| D[Use T: Copy]
C -->|No| E[Use T: Clone]The diagram above is a mermaid block, so it needs the required format. Here it is in the format the platform expects:
Common errors
- Missing bound. Writing
let m = items[0];in a generic function fails with "cannot move out of type[T], a non-copy slice". AddT: Copy, or callitems[0].clone()withT: Clone. - Over-constraining. Requiring
CopywhenClonewould do shuts outString,Vec, and your own types that own heap data. - Bounds on the wrong side.
Vec<T>isCloneonly whenT: Clone. A function that calls.clone()on aVec<T>needsT: Clonein its signature.
Exercise
Why does largest accept &[i32] but largest::<String> fails to compile, and what bound change would let it accept String?
Show answer
String is not Copy, so copied() and by-value returns from a borrowed slice are not allowed. Change the bound to T: Clone and call .clone() on the chosen element, as in largest_cloned.