Theme
Q020. What is the difference between Copy and Clone?
Short Answer
Copy enables implicit duplication in move contexts and has no method or custom runtime behavior. Clone performs explicit duplication through clone() and may allocate, copy a resource, or update reference counts. Every Copy type must also implement Clone, but many Clone types cannot be Copy. Neither trait guarantees that duplication is cheap or deep.
Deep Dive
Copy is a marker trait. The compiler may duplicate a Copy value whenever it is read by value, and the source remains usable. Because this operation is implicit, it cannot run type-specific duplication code.
Clone is an ordinary trait with explicit methods. Its implementation defines the semantics and cost:
String::clonenormally allocates and copies UTF-8 bytes;Vec<T>::clonenormally allocates and clones each element;Rc::cloneincrements a non-atomic reference count;Arc::cloneperforms an atomic reference-count increment;- cloning a scalar simply copies its value.
clone_from may reuse resources already owned by the destination, so even cloning the same type can have different allocation behavior.
Internal Model
A Copy use is represented directly in compiler IR and invokes no trait method at runtime. A clone() call is a normal method call that is statically dispatched for concrete types and can later be inlined and optimized.
Copy requires Clone as a supertrait. For a well-behaved Copy type, explicit clone() should have the same result as copying the value.
Example
rust
fn main() {
let first_number = 42_u64;
let second_number = first_number;
let first_text = String::from("rust");
let second_text = first_text.clone();
println!("{first_number} {second_number}");
println!("{first_text} {second_text}");
}Common Mistakes
- Saying
Clonealways performs a deep copy. - Assuming
.clone()always allocates memory. - Treating
Copyand a cheapCloneas interchangeable API guarantees.
Follow-ups
- Why does
Arc::cloneneed an atomic operation? - How can
clone_fromreuse an existing allocation? - Why should expensive duplication remain explicit?
Related
- Q009. Does Rust ownership have a runtime cost?
- Q019. How does
Copychange assignment and move semantics? - Q021. When can a type implement
Copy?
References
- The Rust Programming Language
- Rust Reference
- Rust Standard Library