Sub topic 6
When a type cannot be Copy
This chapter assumes you can read basic Rust (structs, enums, traits), know how ownership and moves work, and can read compiler error messages. Earlier chapters showed that Copy makes assignment duplicate a value instead of moving it. This chapter covers the other side: the rules that stop a type from being Copy, how to recognize each failure, and what to do about it.
The rule in one sentence
A type can implement Copy only if duplicating its bytes yields a complete, independent, valid value, and nothing needs to run when either duplicate goes away.
The compiler turns that idea into four checks:
- Every field (or every field of every enum variant) must itself be
Copy. - The type must also implement
Clone, becauseCopyis declared aspub trait Copy: Clone. - The type must not implement
Drop. - The
implmust be allowed by the orphan rule, so you can only implementCopyfor types you define.
Copy has no methods. It is a marker trait that tells the compiler to treat a move as a bitwise duplicate. You cannot customize what the copy does, which is why the checks above must be strict.
Rule 1: every field must be Copy
If one field is not Copy, the whole struct cannot be. The usual cause is a field that owns heap memory, such as String, Vec<T> or Box<T>.
// #[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);
}The reason is concrete. A String holds a pointer, a length and a capacity. A bitwise copy would produce two String values pointing at the same heap buffer. Both would try to free it when dropped, which is a double free. Ownership exists to prevent this, so the compiler refuses.
The same rule applies to enums, and it applies per variant. One non-Copy payload in any variant rules out the whole enum:
#[derive(Debug, Clone, Copy)]
enum Shape {
Circle(f64),
Rect { w: f64, h: f64 },
Empty,
}
// #[derive(Clone, Copy)] // error[E0204]: `Named` holds a String
#[derive(Debug, Clone)]
enum Tag {
Id(u32),
Named(String),
}
fn main() {
let s = Shape::Rect { w: 2.0, h: 3.0 };
let t = s;
println!("{:?} {:?} {:?}", s, t, Shape::Circle(1.0));
println!("{:?} {:?}", Tag::Id(1), Tag::Named(String::from("x")));
let _ = Shape::Empty;
}Which field types are the usual offenders
| Field type | Copy? | Why |
|---|---|---|
| `i32`, `f64`, `bool`, `char` | Yes | Plain values |
| `&T` (shared reference) | Yes | Many readers may exist at once |
| `&'static str` | Yes | A shared reference to a string slice |
| `&mut T` | No | Two copies would give two mutable aliases |
| `String`, `Vec<T>`, `Box<T>` | No | They own heap memory |
| `Rc<T>`, `Arc<T>` | No | Cloning must update a reference count |
| `Cell<T>`, `RefCell<T>` | No | Interior mutability needs controlled duplication |
| `[T; N]`, `(A, B)` | Only if every element type is | The impl is conditional |
If a field only needs to read text that lives for the whole program, a &'static str often lets a struct stay Copy:
#[derive(Debug, Clone, Copy)]
struct Label {
id: u32,
name: &'static str,
}
fn main() {
let a = Label { id: 1, name: "home" };
let b = a;
println!("{:?} {:?}", a, b);
}The trade-off is that the text can no longer be built at runtime. For data that is created or changed while the program runs, use String and give up Copy.
Rule 2: Copy requires Clone
Copy: Clone means you cannot implement Copy alone. Deriving both together is the normal pattern:
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
let q = p;
println!("{:?} {:?} {}", p, q, p == q);
}When you write the impls by hand, the Clone body for a Copy type is almost always *self. That is also what the derive produces for a type with no generics.
Rule 3: Copy and Drop are mutually exclusive
If a type implements Drop, it has cleanup code that runs when a value goes out of scope. An implicit copy would create a second value, and the cleanup would run twice. Releasing a file handle, a lock or a network connection twice is a bug, so the compiler forbids the combination with error E0184.
#[derive(Clone)]
struct Guard {
id: u32,
}
impl Drop for Guard {
fn drop(&mut self) {
println!("releasing {}", self.id);
}
}
// impl Copy for Guard {} // error[E0184]: the trait `Copy` cannot be implemented for this type;
// // the type has a destructor
fn main() {
let g = Guard { id: 1 };
let h = g.clone();
println!("created {} and {}", g.id, h.id);
}Running this prints created 1 and 1, then releasing 1 twice, because each clone is an independent value with its own drop. That is acceptable for an explicit clone. It would be a hazard if copies appeared silently on every assignment.
A related point: a type with no Drop impl but with a field that has one is also blocked, because that field is not Copy.
Rule 4: generics make derive conditional
On a generic type, #[derive(Clone, Copy)] adds a bound T: Copy to the generated impl. The derived type is Copy only for those T that are Copy. This is sometimes more restrictive than necessary.
use std::marker::PhantomData;
#[derive(Clone, Copy)]
struct DerivedId<T> {
raw: u32,
_marker: PhantomData<T>,
}
struct User; // not Copy
fn main() {
let a: DerivedId<u32> = DerivedId { raw: 1, _marker: PhantomData };
let b = a; // fine: u32 is Copy
println!("{} {}", a.raw, b.raw);
let c: DerivedId<User> = DerivedId { raw: 2, _marker: PhantomData };
let d = c;
// println!("{}", c.raw); // error[E0382]: borrow of moved value: `c`
let _ = d;
}DerivedId<User> holds only a u32 and a zero-sized marker, so copying it is safe. The derive cannot see that. It requires User: Copy anyway, so c moves. The fix is to write the impls by hand without the bound:
use std::marker::PhantomData;
struct Id<T> {
raw: u32,
_marker: PhantomData<T>,
}
impl<T> Clone for Id<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Id<T> {}
struct User; // not Copy
fn main() {
let a: Id<User> = Id { raw: 7, _marker: PhantomData };
let b = a;
println!("{} {}", a.raw, b.raw);
}The Clone impl uses *self, which is allowed because Id<T> is Copy. This is the standard pattern for typed IDs and handles. The compiler still checks each field, so the manual impl cannot be used to lie about Copy. If you added a String field, it would be rejected.
Rule 5: you can only implement Copy for your own types
The orphan rule says you may implement a trait for a type only if the trait or the type is defined in your crate. Copy and String both come from the standard library, so this fails:
// impl Copy for String {} // error[E0117]: only traits defined in the current crate
// // can be implemented for types defined outside of the crate
fn main() {
println!("String cannot be made Copy by user code");
}You also could not implement it for the reason in Rule 1. To get copy-like behavior around a foreign type, wrap it in your own type, and the wrapper is still subject to the field rule.
Reading the compiler's response
When a Copy derive fails, the error points at the field that is not Copy. Look for:
E0204: some field's type does not implementCopy. Fix the field, or dropCopyand keepClone.E0184: the type has a destructor. RemoveDropor give upCopy.E0382("borrow of moved value") at a use site: the type is notCopy, so the earlier assignment moved it. Borrow it with&, call.clone(), or reconsider the type's design.
What to do instead
When a type cannot be Copy, you still have three options:
- Derive
Cloneand call.clone()where a copy is needed. Duplication then shows up in the source. - Pass
&Tor&mut Tand avoid duplication altogether. - Wrap the data in
Rc<T>orArc<T>when several owners need the same value. Cloning then copies a pointer and bumps a counter, not the contents.
Exercise
A struct Config { retries: u32, host: String } derives Clone and Copy, and the compiler reports E0204. Name two different changes that make the code compile, and say what each one costs.
Show answer
Option 1: remove Copy from the derive and keep Clone. The cost is that assignments now move the value, so you must borrow it or call .clone() explicitly, and each clone allocates a new buffer for host. Option 2: change host to &'static str, which is Copy, so the struct can stay Copy. The cost is that the host text must live for the whole program and cannot be built at runtime. Changing host to Rc<str> would not work, because Rc is not Copy.
Exercise
You write #[derive(Clone, Copy)] struct Handle<T> { raw: u32, _m: PhantomData<T> }. Handle<Widget> is moved on assignment even though it contains only a u32 and a zero-sized marker, and Widget is not Copy. Why does this happen, and how do you fix it?
Show answer
The derive adds a T: Copy bound to the generated Clone and Copy impls, so Handle<Widget> is Copy only if Widget is. The fix is to remove the derive and write impl<T> Clone for Handle<T> { fn clone(&self) -> Self { *self } } and impl<T> Copy for Handle<T> {}, which carry no bound on T.