Skip to content

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::clone normally allocates and copies UTF-8 bytes;
  • Vec<T>::clone normally allocates and clones each element;
  • Rc::clone increments a non-atomic reference count;
  • Arc::clone performs 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 Clone always performs a deep copy.
  • Assuming .clone() always allocates memory.
  • Treating Copy and a cheap Clone as interchangeable API guarantees.

Follow-ups

  • Why does Arc::clone need an atomic operation?
  • How can clone_from reuse an existing allocation?
  • Why should expensive duplication remain explicit?

References

  • The Rust Programming Language
  • Rust Reference
  • Rust Standard Library