Sub topic 9
Using Copy and Clone as Generic Bounds
This chapter assumes you know Rust's basic syntax, ownership and borrowing, and how to read compiler errors. You should also know what Copy and Clone are and how they differ. Here you will see how to use them as trait bounds on generic code, what each bound promises, and which mistakes come up most often.
What a bound promises
A generic function does not know what T is. The compiler lets you do only what the bounds on T allow. Without a bound, you can move a T or take a reference to it, and that is all.
T: Clonesays that.clone()exists. The caller may pay any cost for it, and the function must call it explicitly.T: Copysays thatTis duplicated by a plain assignment. The original stays usable after a move-like use.CopyhasCloneas a supertrait, soT: Copyalso lets you call.clone().
Because Copy: Clone, you never need to write T: Copy + Clone. The Clone part is redundant, although it compiles.
Why a function needs Copy
Reading an element out of a slice by value is the classic case. A slice only lends you its elements, so you cannot move one out.
fn first<T>(items: &[T]) -> T {
items[0]
}This does not compile. The compiler reports that it cannot move out of type [T], a non-copy slice. Two bounds fix it, and they fix it in different ways.
fn first_copy<T: Copy>(items: &[T]) -> T {
items[0]
}
fn first_clone<T: Clone>(items: &[T]) -> T {
items[0].clone()
}
fn main() {
println!("{}", first_copy(&[7, 8, 9]));
let names = vec![String::from("Ada"), String::from("Grace")];
println!("{}", first_clone(&names));
}first_copy works for integers, floats, char, bool, and your own Copy structs. It rejects String. first_clone accepts everything in first_copy, and it also accepts String, Vec<T>, and Rc<T>. The cost is that an expensive type does real work on each call.
Choosing between the two bounds
Pick the weaker bound that lets your function do its job. Clone is weaker than Copy, since every Copy type is also Clone. A function bounded by Clone is therefore callable with more types.
| Bound | Accepts | Call site looks like | Hidden cost |
|---|---|---|---|
| none | any type | cannot duplicate | none |
| `T: Clone` | `i32`, `String`, `Vec<T>`, `Rc<T>` | `x.clone()` | can be a heap allocation |
| `T: Copy` | `i32`, `char`, small plain structs | `x` | a bitwise copy of `size_of::<T>()` bytes |
Use Copy when it makes the body simpler and the callers are small value types, such as numeric code. Use Clone when callers may pass owned data like strings.
A worked example with Copy
The largest function below needs to compare items and return one by value. PartialOrd provides >, and Copy lets it hand back an element without moving it out of the slice.
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. Three details matter:
items.iter()yields&T. The adapter.copied()turns each&Tinto aT, and it requiresT: Copy. Its counterpart.cloned()requires onlyT: Clone.- The
?operator initer.next()?returnsNoneearly for an empty slice. This is why the function returnsOption<T>and does not panic. largest::<f64>(&[])needs the turbofish because an empty array literal gives the compiler nothing to inferTfrom.
Passing &["a".to_string()] to largest fails to compile with an error that String does not implement Copy. That error points at the bound, which is where you want it.
Relaxing the bound to Clone
You can rewrite largest to work on String by swapping Copy for Clone and using .cloned(). The code below does that, and it avoids cloning during the scan by holding a reference to the best item.
fn largest_cloned<T: PartialOrd + Clone>(items: &[T]) -> Option<T> {
let mut best = items.first()?;
for x in &items[1..] {
if x > best {
best = x;
}
}
Some(best.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 prints Some("zebra") and then Some(9). The scan compares &T against &T, and exactly one clone happens, at the end. A version that cloned every element on the way would allocate once per String, with the same result. The Clone bound opens the function to more types, and good code still keeps clones out of the loop.
Where to put the bound
Bounds can sit on the function, on an impl block, or on a single method. The location decides who is affected.
use std::fmt::Debug;
#[derive(Debug)]
struct Pair<T> {
a: T,
b: T,
}
impl<T> Pair<T> {
fn new(a: T, b: T) -> Self {
Pair { a, b }
}
fn swap(self) -> Pair<T> {
Pair { a: self.b, b: self.a }
}
}
impl<T: Clone> Pair<T> {
fn duplicate_first(&self) -> Pair<T> {
Pair { a: self.a.clone(), b: self.a.clone() }
}
}
impl<T: Copy + Debug> Pair<T> {
fn show_both_twice(&self) {
let Pair { a, b } = *self;
println!("{:?} {:?}", a, b);
println!("{:?} {:?}", a, b);
}
}
fn main() {
let p = Pair::new(1, 2);
p.show_both_twice();
let q = p.duplicate_first();
println!("{:?}", q);
let s = Pair::new(String::from("x"), String::from("y")).swap();
println!("{:?}", s);
}Pair<String> has new and swap. It lacks show_both_twice, because String is not Copy. Method availability depends on T, and no part of the struct itself is restricted. This is usually better than bounding the struct definition with struct Pair<T: Copy>, because a bound on the struct forces every impl and every user of the type to repeat it.
In show_both_twice, the line let Pair { a, b } = *self; moves fields out of a reference. It compiles only because T: Copy. Without that bound, the compiler would report that it cannot move out of *self, which is behind a shared reference.
Derives add bounds you did not write
#[derive(Clone)] on a generic struct produces impl<T: Clone> Clone for Pair<T>. The same applies to Copy. Deriving Copy on Pair<T> gives impl<T: Copy> Copy for Pair<T>, so Pair<i32> is Copy and Pair<String> is not. The derive adds the bound to every type parameter, and that has one consequence you should know about.
use std::rc::Rc;
#[derive(Clone)]
struct Handle<T> {
inner: Rc<T>,
}
struct NotClone;
fn main() {
let h = Handle { inner: Rc::new(5) };
let _h2 = h.clone();
let _n = Handle { inner: Rc::new(NotClone) };
// let _n2 = _n.clone(); // error: `NotClone` does not implement `Clone`
}Cloning an Rc<T> never needs T: Clone, because it copies the pointer. The derived impl still demands T: Clone, so Handle<NotClone> cannot be cloned. The fix is a manual impl without the extra bound.
use std::rc::Rc;
struct Handle<T> {
inner: Rc<T>,
}
impl<T> Clone for Handle<T> {
fn clone(&self) -> Self {
Handle { inner: Rc::clone(&self.inner) }
}
}
struct NotClone;
fn main() {
let n = Handle { inner: Rc::new(NotClone) };
let _n2 = n.clone();
println!("{}", Rc::strong_count(&n.inner));
}This prints 2. Use a manual impl whenever a derive's blanket bound is stricter than the real requirement of your fields.
Bounds on references and the Copy of &T
Shared references &T are Copy for every T, even when T itself is not. Mutable references &mut T are never Copy. This matters when a generic parameter is itself a reference type.
fn twice<T: Copy>(x: T) -> (T, T) {
(x, x)
}
fn main() {
let s = String::from("shared");
let r = &s;
let (a, b) = twice(r);
println!("{a} {b}");
}Here T is &String, which is Copy, so the call compiles. Replacing r with &mut s would fail, because &mut String is not Copy.
Where clauses and `impl Trait`
When bounds grow, use a where clause for readability. The meaning is the same.
use std::fmt::Display;
fn repeat_labelled<T>(item: &T, times: usize) -> Vec<String>
where
T: Clone + Display,
{
(0..times)
.map(|i| {
let owned = item.clone();
format!("{i}: {owned}")
})
.collect()
}
fn main() {
for line in repeat_labelled(&"tag", 3) {
println!("{line}");
}
}In argument position, impl Clone is shorthand for an anonymous bound: fn f(x: impl Clone). It is not available when you need to name the type twice, so fn pair<T: Copy>(a: T, b: T) cannot be written with impl.
How the compiler checks a bound
Bounds are checked at the call site, once per distinct type, when the function is instantiated. Generic functions are monomorphized, so largest::<i32> and largest::<f64> become separate machine code. A Copy bound has no runtime cost of its own. It only grants the right to treat the value as copyable.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `cannot move out of type [T], a non-copy slice` | Indexing by value without a bound | Add `T: Copy`, or call `.clone()` with `T: Clone` |
| `the trait bound String: Copy is not satisfied` | Caller passed an owning type to a `Copy` function | Relax the bound to `Clone` or pass a reference |
| `no method named clone found for type parameter T` | The `Clone` bound is missing | Add `T: Clone` |
| `cannot move out of *self which is behind a shared reference` | Destructuring through `&self` | Add `T: Copy`, or clone the specific fields |
| A generic struct cannot be cloned though its fields can | Derive added `T: Clone` to every parameter | Write `impl<T> Clone` by hand |
Design checklist
- Start with no bound and a reference parameter.
- Add
Cloneif the function must produce an owned value from a borrowed one. - Add
Copyonly if the function is meant for small plain values and copy semantics simplify the body. - Keep clones out of loops when a reference works.
- Put the bound on the
implor the method rather than on the struct. - Check whether a derive's blanket bound is stricter than your fields need.
Exercise
You write fn pick<T: Clone>(a: &T, b: &T, first: bool) -> T, and it returns a.clone() or b.clone(). A colleague proposes changing the bound to T: Copy and returning *a or *b. Name one type that works with the original but breaks with the proposal, and say what each version costs for that type.
Show answer
String (or Vec<i32>) works with Clone but is rejected by Copy. With Clone, each call allocates and copies the heap data of the chosen argument. With Copy, a String call does not compile. For i32, both versions cost the same, since Clone on a Copy type is a plain copy. The Clone bound is the more general choice.
Exercise
#[derive(Clone)] struct Shared<T> { data: std::sync::Arc<T> } fails to clone for Shared<std::cell::Cell<u8>>, even though cloning an Arc is always allowed. Why, and how do you fix it?
Show answer
The derive generates impl<T: Clone> Clone for Shared<T>, so the type parameter must be Clone. Cell<u8> is not Clone for this purpose in the way the derive requires, and in general the bound is stricter than needed. Remove the derive and write impl<T> Clone for Shared<T> { fn clone(&self) -> Self { Shared { data: std::sync::Arc::clone(&self.data) } } }, which clones only the Arc pointer.