Sub topic 6
When a type cannot be Copy
This chapter assumes you know Rust structs, enums and traits, the basics of ownership and borrowing, and how to read compiler errors. You have already seen that #[derive(Clone, Copy)] makes a type duplicate on assignment. Here you learn when the compiler refuses that derive, and why.
The two rules
A type can implement Copy only if both of these hold:
- Every field (or every enum variant's payload) is itself
Copy. - The type does not implement
Drop.
Copy also requires Clone, because Copy is declared as a subtrait: trait Copy: Clone. If you write impl Copy or derive(Copy), Clone must be implemented too.
Rule 1: all fields must be Copy
A Copy value is duplicated by a plain bitwise copy of its bytes. That is only safe if every field can be duplicated that way. A String owns a heap buffer. Copying its bytes would give two String values that point to the same buffer, and both would try to free it when dropped.
// #[derive(Clone, Copy)] // error: 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);
}If you remove the comment on the derive line, the compiler points at the name field and says it does not implement Copy. The fix is not to force the derive. Either keep the type Clone only, or change the field to a type that is Copy, such as &'static str or a small integer id.
Types that commonly block Copy:
| Field type | Why it is not Copy |
|---|---|
| `String`, `Vec<T>`, `Box<T>` | Owns heap memory |
| `Rc<T>`, `Arc<T>` | Copying would skip the reference count update |
| `&mut T` | Two live mutable references would break aliasing rules |
| `File`, `MutexGuard<T>` | Owns a resource that must be released once |
Shared references &T are Copy, so a struct holding only &T fields can be Copy. Tuples, arrays and Option<T> are Copy when their contents are.
Rule 2: no Drop
A type with a Drop implementation runs cleanup code when a value goes out of scope. If such a type were Copy, the compiler would have to run the cleanup once per copy. It would also be easy to release a resource twice. The compiler therefore rejects the combination.
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
println!("released");
}
}
// impl Clone for Guard { fn clone(&self) -> Self { Guard } }
// impl Copy for Guard {} // error: the trait `Copy` cannot be implemented for this type; the type has a destructor
fn main() {
let _g = Guard;
}If a type has a destructor, it is meant to own something. Treat that as a sign it should move, not copy.
Enums follow the same rule
For an enum, the check covers every variant. One non-Copy payload in any variant rules out the whole enum.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Shape {
Circle(f64),
Rect(f64, f64),
}
// Adding `Label(String)` to Shape would make `derive(Copy)` fail.
fn main() {
let a = Shape::Circle(1.5);
let b = a;
println!("{:?} {:?}", a, b);
}Generic types
#[derive(Copy)] on a generic struct adds a bound T: Copy to the generated impl. So Wrapper<i32> is Copy, while Wrapper<String> is only as capable as its Clone impl allows.
#[derive(Debug, Clone, Copy)]
struct Wrapper<T> {
value: T,
}
fn main() {
let a = Wrapper { value: 7 };
let b = a;
println!("{:?} {:?}", a, b);
let s = Wrapper { value: String::from("x") };
let t = s.clone(); // Clone works only if String: Clone, which it is
println!("{:?}", t);
}The type Wrapper<String> is not Copy, so let u = s; would move s.
A diagram of the decision
Exercise
A struct has fields id: u32, tag: &'static str and buf: Vec<u8>. Why does #[derive(Clone, Copy)] fail, and what are two ways to resolve it?
Show answer
Vec<u8> owns heap memory and is not Copy, so the struct cannot be Copy. You can drop Copy from the derive and use Clone only, or replace buf with a Copy type, such as a fixed-size array [u8; 16] or a &'static [u8].
Exercise
Why can a type that implements Drop never implement Copy?
Show answer
Copies would each run the destructor, so a resource could be released more than once. The compiler rejects Copy on any type with a destructor.