Sub topic 11
Deciding whether your type should be Copy
This chapter assumes you know how moves work, how #[derive(Clone, Copy)] behaves, and why a type holding a String cannot be Copy. Here the question is design: given a new type, should it be Copy, Clone only, or neither?
Copy is a promise you cannot take back
Implementing Copy changes how every assignment and function call involving your type behaves. Code that moved the value before now silently duplicates it. Adding Copy later is usually safe for callers. Removing it breaks any code that used a value after passing it along. Treat Copy as part of your public API.
Adding a non-Copy field to a Copy struct later also breaks the derive, so the decision constrains how the type can grow.
A checklist
Make a type Copy only if all of these hold:
- Every field is
Copy. - The type is small, roughly a few machine words. Copies are bitwise, so a large
Copyarray is duplicated on every call. - A duplicate means the same thing as the original. Two copies of a point are just two points.
- The type does not represent a unique resource, such as a file handle, a lock guard, or an ID that must not be reused.
- You do not expect to add owning fields soon.
If a type fails any of these, use Clone only, or neither.
Examples
A small value type is a good fit:
#[derive(Debug, Clone, Copy, PartialEq)]
struct Rgb {
r: u8,
g: u8,
b: u8,
}
fn darken(c: Rgb) -> Rgb {
Rgb { r: c.r / 2, g: c.g / 2, b: c.b / 2 }
}
fn main() {
let red = Rgb { r: 200, g: 10, b: 10 };
let dark = darken(red);
println!("{:?} {:?}", red, dark);
}red is still usable after darken(red), which is what callers expect from a color.
A unique resource should not be Copy, and often not Clone either:
struct SessionToken {
id: u64,
}
impl SessionToken {
fn new(id: u64) -> Self {
SessionToken { id }
}
fn revoke(self) {
println!("revoked {}", self.id);
}
}
fn main() {
let token = SessionToken::new(7);
token.revoke();
// token.revoke(); // error: use of moved value: `token`
}Because revoke takes self by value and the type is not Copy, the compiler prevents revoking twice. Deriving Copy would remove that guarantee.
Size matters
There is no fixed cutoff, but a common rule is to keep Copy types within about 16 to 32 bytes. For larger types, passing &T avoids copying. The compiler may optimize copies away, so measure before worrying. The semantic reasons in the checklist matter more than size.
Enums and `Copy`
Fieldless enums are nearly always good Copy candidates:
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction {
North,
South,
East,
West,
}An enum with even one non-Copy variant field, such as Message(String), cannot be Copy.
Common mistakes
- Deriving
Copyon a counter or ID generator. Copying it produces two independent counters that hand out the same values. - Deriving
Copyon a type with a mutating method. Amutcopy changes only the copy, which surprises callers who expected in-place updates. - Making a large struct
Copyfor convenience, then paying for it on every call.
Summary of defaults
| Type kind | Recommendation |
|---|---|
| Small plain data (points, colors, fieldless enums) | `Clone` and `Copy` |
| Owns heap data (`String`, `Vec`) | `Clone` only |
| Unique resource or capability | Neither, or `Clone` with care |
| Large plain data | `Clone` only, pass by reference |
Exercise
You are writing struct Counter { next: u32 } with a method fn take(&mut self) -> u32 that returns the next ID and increments. Should Counter derive Copy? Why or why not?
Show answer
No. All fields are Copy, but a copy would be an independent counter. let mut b = a; followed by b.take() would not advance a, so both could issue the same IDs. Without Copy, assignment moves the counter and only one owner can issue IDs. Derive Clone only if duplicating a counter is meaningful.
Exercise
A struct has three f64 fields and derives Clone and Copy. Later you add a label: String field. What happens, and what must you change?
Show answer
The derive of Copy fails to compile, because String is not Copy. Remove Copy from the derive list, keep Clone, and fix every place that relied on implicit copies, for example by borrowing or calling .clone().