`Copy` and `Clone`
Clone is an explicit duplication. Copy is an implicit bitwise clone. You derive both for simple value types; you implement Clone only when duplication has a cost or a policy.
Detailed Explanation
Clone::clone(&self) -> Self is a method. You call it. For String it allocates and copies bytes. For Vec<T> it clones every element. For Arc<T> it bumps a counter. The trait is the "I need another one" hook, and the cost is whatever the implementor says.
Copy is a marker: clone is just memcpy, and the compiler is allowed to do it implicitly on assign. Copy requires Clone. A type with a destructor cannot be Copy. A type that contains a String cannot be Copy. #[derive(Copy, Clone)] on a struct of integers is the usual form.
Derive Clone on almost every plain data struct. It is the difference between a usable test fixture and a struct you cannot duplicate. Implement Clone by hand when a field should not be cloned as-is (a unique id you regenerate, a cache you drop). Do not implement Copy for anything that is expensive to memcpy or that you want people to pass by reference.
clone in a loop is a performance smell. clone to satisfy the borrow checker on a String you could have borrowed is a design smell. Arc::clone is the one clone that is usually the right shared-ownership tool.
When you derive both: small value types, ids, flags, Copy newtypes around integers. When you derive Clone only: anything with a String or Vec. When you implement neither: types that own a unique resource (a file descriptor wrapper) and should not be duplicated.
Manual Clone impls should clone what derive would, unless you have a reason to drop a cache or mint a new id. A Clone that secretly shares an Rc field while duplicating the rest is fine if documented. A Clone that mutates a global is a bug. Keep clone free of side effects besides allocation.
Code Examples
#[derive(Clone, Debug)]
struct Session {
user_id: u64,
token: String,
}
fn main() {
let a = Session { user_id: 1, token: "abc".into() };
let b = a.clone();
println!("{} {}", a.token, b.token); // prints: abc abc
let n = 4;
let m = n; // Copy, no clone() needed
println!("{n} {m}"); // prints: 4 4
}Common Gotchas
`#[derive(Copy)]` on a large struct copies silently
Reviewers should notice a `Copy` on anything bigger than a couple of words.
`Drop` and `Copy` cannot coexist
A type that frees a resource is not `Copy`. That is a compile error if you try both.
`clone` of `Arc` is cheap; `clone` of the inner `T` is not
Write `Arc::clone(&x)` versus `(*x).clone()` on purpose.
Derived `Clone` clones every field
A cache field you forgot about will be cloned too. Use `#[derive(Clone)]` only when that is correct, or write the impl.