Sub topic 11
Deciding whether your type should be Copy
This chapter assumes you know Rust structs, enums, traits, and the basics of ownership and borrowing. You should also know how to derive traits and what a move is. By the end, you will have a checklist for choosing between Copy, Clone only, or neither for a new type.
Why this decision matters
Adding Copy to a type is easy. Removing it later is hard. Once a type is Copy, callers write code that relies on it. They pass values by value and reuse them afterwards, and they never call .clone(). If you later add a String field, every one of those call sites stops compiling.
So treat Copy as part of your public API. It is a promise that the type will always be a small, plain bit pattern.
The decision flow
Start with what the type holds, then ask how it behaves.
The sections below explain each question.
Question 1: Can the type be Copy at all?
A struct or enum can be Copy only if every field is Copy. A type that owns heap memory or a unique resource can never qualify. Examples include String, Vec<T>, Box<T>, and File. A &mut T is not Copy either, because two copies would give two live mutable references to the same data. A type also cannot implement both Copy and Drop.
If this check fails, the choice is between Clone only and neither. The rest of the flow does not apply.
Question 2: Is it a small, plain value?
Copy makes every assignment, function call, and return a silent duplicate. This is cheap for small values, but it is hidden. A large Copy type copies its bytes each time, and the compiler gives you no hint.
Good candidates for Copy share these traits:
- They are small. A rough guide is a few machine words, such as 16 to 32 bytes.
- They represent a value, not a resource. Points, colors, IDs, flags, durations, and small enums are values.
- Two copies are interchangeable. Nothing breaks if both exist.
- They have no identity that matters. Two
Point { x: 1, y: 2 }values are the same point.
Poor candidates, even when every field happens to be Copy:
- A large fixed-size array wrapper, such as a 4 KiB buffer. Each pass by value copies 4 KiB.
- A handle that stands for a unique thing, such as a connection ID that must be closed exactly once. A copy lets two places believe they own it.
- A token or capability that should be used once. Moves exist to enforce this, and
Copyremoves the protection.
The following example shows the last case. A one-use token is easy to misuse if it is Copy.
#[derive(Debug)]
struct Ticket {
id: u32,
}
fn redeem(ticket: Ticket) {
println!("redeemed {}", ticket.id);
}
fn main() {
let t = Ticket { id: 7 };
redeem(t);
// redeem(t); // error: use of moved value: `t`
}Because Ticket is not Copy, the compiler rejects a second redemption. If you added Copy, the second call would compile and the bug would reach runtime.
Question 3: Will it stay that way?
Even a type that qualifies today may not tomorrow. Consider an ID type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct UserId(u64);
fn main() {
let a = UserId(42);
let b = a;
println!("{:?} {:?}", a, b);
}UserId is a good Copy type. It wraps one integer and has no resource semantics. Now suppose a later version adds a name: String field for caching. That change breaks every caller that copied a UserId.
Ask whether the type's shape is stable. Types in a published library need extra care. For a private type used in a single crate, you can fix any breakage in one commit, so the risk is small.
Derive Copy together with Clone
Copy has Clone as a supertrait, so you must implement both. In practice, derive both.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Rgb {
r: u8,
g: u8,
b: u8,
}
fn brighten(c: Rgb) -> Rgb {
Rgb {
r: c.r.saturating_add(20),
g: c.g.saturating_add(20),
b: c.b.saturating_add(20),
}
}
fn main() {
let base = Rgb { r: 100, g: 200, b: 250 };
let light = brighten(base);
println!("{:?} -> {:?}", base, light);
}brighten takes c by value, and base is still usable afterward. With a three-byte type, passing by value is at least as cheap as passing a reference.
If you write Clone by hand for a Copy type, keep it as *self. Clippy warns when a Copy type has a Clone implementation that does anything else.
#[derive(Debug, Copy)]
struct Meters(f64);
impl Clone for Meters {
fn clone(&self) -> Self {
*self
}
}
fn main() {
let m = Meters(2.5);
let n = m.clone();
println!("{:?} {:?}", m, n);
}Question 4: If not Copy, should it be Clone?
For types that cannot or should not be Copy, the next choice is Clone only. Derive Clone when a duplicate is a meaningful operation and callers might reasonably want one.
- A configuration struct, a parsed document, or a list of records: duplicating is sensible, and the cost is visible at the
.clone()call. - A type wrapping
RcorArc: cloning is cheap and gives shared ownership.
Skip Clone when a duplicate would break an invariant.
- A type that represents unique ownership of an external resource, such as a file descriptor or a lock guard.
Filehastry_cloneinstead ofClone, because duplicating a descriptor can fail. - A type whose purpose is to be used once, like the
Ticketabove. - A type where a copy would be misleading, such as a unique ID generator.
A type with neither trait is still fully usable. Callers pass it by value or by reference, and the compiler enforces single ownership.
Summary table
| Situation | Choice | Reason |
|---|---|---|
| Small plain value, all fields `Copy`, stable shape | `Clone` and `Copy` | Cheap, natural, ergonomic |
| Owns heap data, duplication is sensible | `Clone` only | Cost is visible in `.clone()` |
| Shared ownership wrapper | `Clone` only | `Rc` and `Arc` clones are cheap |
| Unique resource or single-use token | Neither | A move enforces the invariant |
| Large fixed-size value | `Clone` only, or neither | Silent copies would be expensive |
Checking the cost with a size assertion
If you want to guard a Copy type against growing, add a compile-time size check. This is useful in a library where a field addition could silently inflate every copy.
use std::mem::size_of;
#[derive(Debug, Clone, Copy)]
struct Span {
start: u32,
end: u32,
}
const _: () = assert!(size_of::<Span>() <= 16);
fn main() {
println!("Span is {} bytes", size_of::<Span>());
}The const _ item runs at compile time. If someone adds fields that push Span past 16 bytes, the build fails and prompts a review of whether Copy still makes sense.
Edge cases
- Generic structs.
#[derive(Clone, Copy)]onstruct Pair<T>(T, T)adds aT: Copybound.Pair<String>is notCopy, butPair<i32>is. This is usually what you want. - Enums. An enum can be
Copyonly if every variant's fields areCopy. A fieldless enum is almost always a goodCopycandidate. - Floats.
f64isCopy, so a type holding floats can beCopy. It can derivePartialEqbut notEqorHash, because ofNaN. - Interior mutability.
Cell<T>is notCopyeven whenTis. Copying a cell would break the sharing guarantees it relies on. - Mutation after copy. A copy is independent. If
aisCopyand you dolet mut b = a; b.x = 9;,ais unchanged. Developers coming from reference-based languages sometimes expect the opposite.
Common mistakes
- Adding
Copyto avoid writing&. It works, but it hides the intent. If the type is large, you pay for it everywhere. - Adding
Copyto silence a borrow-checker error. This often means the design needs a reference or aClone. Making a typeCopyjust to compile can change program meaning, because mutations now apply to copies. - Adding
Cloneeverywhere by reflex. An unneededCloneimplementation invites.clone()calls that mask ownership problems. - Forgetting that removing
Copyis a breaking change. In a public crate, addingCopylater is compatible. Removing it is not.
Quick checklist
- Does every field implement
Copy? If not, stop: noCopy. - Is the type small, a plain value, and free of resource semantics? If not, skip
Copy. - Is the shape unlikely to change? If not, be cautious, especially in a public API.
- If you skip
Copy, is duplication meaningful? If yes, deriveClone. If not, derive neither. - If you derive
Copy, deriveClonetoo, and keep any manualCloneas*self.
Exercise
You define struct Session { id: u64, token: String }. A teammate suggests adding #[derive(Clone, Copy)] so sessions are easier to pass around. Explain whether this works and what you would derive instead.
Show answer
It does not compile. String is not Copy because it owns heap memory, so Session cannot be Copy. Derive Clone only if duplicating a session is meaningful, for example to log or cache it. If a session represents a unique login that must not exist twice, derive neither and pass it by value or by reference.
Exercise
A type Handle(u32) wraps an ID for a resource that must be released exactly once through fn release(self). All fields are Copy. Should it be Copy? Why?
Show answer
No. Although it could be, a Copy handle lets the same ID be released twice, because the compiler no longer reports use after move. Leaving it non-Copy makes release(self) consume the handle, so the compiler rejects a second call.
Exercise
Why does a type that implements Copy also need to implement Clone, and what should clone do in that case?
Show answer
Clone is a supertrait of Copy, so any Copy type must implement it. Its clone should simply return *self, which is a bitwise copy. Deriving both gives exactly that behavior.