Sub topic 5
Deriving Clone and Copy on Your Own Types
This chapter assumes you know Rust structs, enums and traits, and the basics of ownership and borrowing. It also assumes you can read compiler error messages. The earlier chapters covered what Copy and Clone mean. This one covers how to get them onto your own types with #[derive(...)], what the derive generates, and why it sometimes refuses.
What `derive` does
A derive attribute asks the compiler to write a trait implementation for you. For Clone, the generated code clones every field in turn and builds a new value. For Copy, the generated code is an empty marker implementation, because Copy has no methods. The compiler copies the bits whenever a value is used after assignment.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
let q = p; // copied, not moved
println!("{:?} {:?}", p, q);
}Without Copy, the line let q = p; would move p, and the println! would fail to compile with "borrow of moved value". Adding Copy is what keeps p usable.
`Copy` requires `Clone`
Copy is declared as trait Copy: Clone. Clone is a supertrait of Copy, so every Copy type must also be Clone. Writing #[derive(Copy)] alone fails with an error saying the trait bound Point: Clone is not satisfied. In practice you always derive them as a pair:
#[derive(Clone, Copy)]
struct Meters(f64);The order inside the list does not matter. When you derive both on a type with no generic parameters, the generated clone simply returns *self. Cloning a Copy type is therefore a plain bitwise copy.
What the derive expands to
Deriving Clone on a struct is roughly equivalent to this manual code:
struct Point {
x: i32,
y: i32,
}
impl Clone for Point {
fn clone(&self) -> Self {
Point {
x: Clone::clone(&self.x),
y: Clone::clone(&self.y),
}
}
}
impl Copy for Point {}
fn main() {
let a = Point { x: 3, y: 4 };
let b = a.clone();
let c = a;
println!("{} {} {}", a.x, b.y, c.x);
}Every field must itself implement Clone. If one field does not, the derive fails with an error that names the field type. The derive does not skip fields or substitute defaults.
Structs, tuple structs, unit structs and enums
The derive works on every shape of type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction {
North,
East,
South,
West,
}
#[derive(Debug, Clone, Copy)]
enum Shape {
Circle { radius: f64 },
Rect { w: f64, h: f64 },
}
#[derive(Debug, Clone, Copy)]
struct Marker; // unit struct
fn main() {
let d = Direction::North;
let e = d;
let s = Shape::Rect { w: 2.0, h: 3.0 };
let t = s;
println!("{:?} {:?} {:?} {:?} {:?}", d, e, s, t, Marker);
println!("{:?}", Shape::Circle { radius: 1.0 });
}For an enum, Copy requires that every field of every variant be Copy. A single String in one variant removes Copy from the whole enum. Fieldless enums such as Direction are the easiest Copy candidates.
When the derive fails
These are the errors you meet most often.
| Situation | Result |
|---|---|
| `derive(Copy)` on a type with a `String`, `Vec`, or `Box` field | Error E0204: `Copy` cannot be implemented for this type |
| `derive(Copy)` without `Clone` | Error: the trait bound `T: Clone` is not satisfied |
| `Copy` on a type that implements `Drop` | Error E0184: the type cannot implement both `Copy` and `Drop` |
| `derive(Clone)` on a type with a `&mut T` field | Error: `&mut T` is not `Clone` |
| `derive(Clone)` on a type with a field whose type has no `Clone` | Error naming that field's type |
The third row has a clear reason. A Copy value can be duplicated at any time without running code, so no destructor could run safely once per copy. The &mut T row has the same kind of reason. Two copies of an exclusive reference would break the rule that only one mutable borrow exists.
Shared references are different. &T is both Clone and Copy, so a struct holding &str or &T can derive both traits.
#[derive(Debug, Clone, Copy)]
struct Label<'a> {
id: u32,
text: &'a str,
}
fn main() {
let l = Label { id: 1, text: "ready" };
let m = l;
println!("{:?} {:?}", l, m);
}Here is a struct that can derive Clone but not Copy:
// #[derive(Clone, Copy)] // error[E0204]: the trait `Copy` cannot be implemented for this type
#[derive(Debug, Clone)]
struct User {
id: u32,
name: String,
}
fn main() {
let u = User { id: 1, name: String::from("Ada") };
let v = u.clone();
println!("{:?} {:?}", u, v);
}User is still useful. Assignment moves it, and .clone() makes a deep copy of the String on demand.
Generic types: the bound the derive adds
When a type has generic parameters, the derive adds a bound on each parameter. For struct Pair<T>, the derive produces impl<T: Clone> Clone for Pair<T> and impl<T: Copy> Copy for Pair<T>. The result is that Pair<T> is Copy only when T is Copy.
#[derive(Debug, Clone, Copy)]
struct Pair<T> {
a: T,
b: T,
}
fn main() {
let nums = Pair { a: 1, b: 2 };
let n2 = nums; // Pair<i32> is Copy
println!("{:?} {:?}", nums, n2);
let words = Pair { a: String::from("x"), b: String::from("y") };
let w2 = words.clone(); // Pair<String> is Clone but not Copy
println!("{:?} {:?}", words, w2);
}This shows that Copy-ness is conditional. The same generic type can be Copy for one T and move-only for another.
The over-eager bound
The derive adds T: Clone for every type parameter, even when no field needs it. This surprises people with pointer-like wrappers. Suppose T appears only behind an Rc:
use std::rc::Rc;
struct Opaque; // deliberately not Clone
struct Shared<T> {
inner: Rc<T>,
}
impl<T> Clone for Shared<T> {
fn clone(&self) -> Self {
Shared {
inner: Rc::clone(&self.inner),
}
}
}
fn main() {
let a = Shared { inner: Rc::new(Opaque) };
let b = a.clone();
println!("{}", Rc::strong_count(&a.inner));
println!("{}", Rc::ptr_eq(&a.inner, &b.inner));
}This prints 2 and then true. If you had written #[derive(Clone)] on Shared<T>, the call a.clone() would fail to compile. The compiler would report that the method exists but its trait bounds were not satisfied, because Opaque is not Clone. Cloning an Rc never clones the contents, so the derived bound is stricter than it needs to be. The fix is a manual implementation with no bound on T, as above. The next chapters return to hand-written Clone.
Choosing what to derive
The last question in the diagram is a design decision, not a compiler rule. The compiler allows Copy on a large array struct, but every use of the variable then copies it. Marking a type Copy is also hard to undo. Once callers rely on let q = p; leaving p usable, removing Copy breaks their code. Adding Copy later is a safe change, so when unsure, start with Clone only.
Common mistakes
- Deriving
Copyto silence a move error. If aStringfield blocksCopy, adding.clone()where needed is the correct fix. Replacing theStringwith&'static stronly makes sense if the text really is static. - Forgetting that a derived trait applies to every field. One new non-
Copyfield added to aCopystruct breaks every place that copied it. The error appears at the derive, not at the new field's use. - Calling
.clone()on aCopytype. It works, and it is the same as a plain copy, but Clippy flags it underclone_on_copy. Drop the call. - Assuming derived
Cloneis cheap. It clones every field. For a struct holding aVec<String>, that is a full deep copy. - Hand-writing
Cloneon aCopytype. A manualCloneon aCopytype should behave exactly like a bitwise copy. Anything else makesx.clone()andlet y = x;disagree. Clippy'sexpl_impl_clone_on_copylint warns about this pattern.
Exercise
You write #[derive(Clone, Copy)] struct Config { name: String, retries: u32 }. The compiler reports error E0204. State the cause and give two valid fixes.
Show answer
String owns heap memory and is not Copy, so a struct containing it cannot be Copy. Fix 1: remove Copy and keep #[derive(Clone)], then call .clone() when you need a duplicate. Fix 2: change the field to a Copy type such as &'static str (adding a lifetime parameter if the text is not static), which allows both derives.
Exercise
Given #[derive(Clone, Copy)] struct Wrapper<T> { value: T }, is Wrapper<String> Clone? Is it Copy? What about Wrapper<i32>?
Show answer
The derive generates impl<T: Clone> Clone and impl<T: Copy> Copy. Wrapper<String> is Clone (since String: Clone) but not Copy (since String is not Copy). Wrapper<i32> is both Clone and Copy.
Exercise
A struct Handle<T> { data: Rc<T> } uses #[derive(Clone)]. Calling .clone() fails when T has no Clone impl, even though cloning an Rc never clones T. Why does this happen, and how do you fix it?
Show answer
The derive adds a T: Clone bound to the generated impl for every type parameter, whether or not a field needs it. Remove the derive and write impl<T> Clone for Handle<T> by hand, with fn clone(&self) -> Self { Handle { data: Rc::clone(&self.data) } }. That impl has no bound on T.