In this lesson, you will learn how to use the Clone trait to create deep copies of heap-allocated data, allowing you to bypass strict move semantics when you need two independent owners of the same information.
Why Moves Block Access
As you learned in our previous lessons, Rust's move semantics are designed to prevent memory bugs like "double-free" errors. When you assign a heap-allocated type (like a String or Vec) to a new variable, ownership moves. The original variable becomes invalid, and you can no longer use it.
let original = String::from("Hello");
let moved = original;
// println!("{}", original); // Error! 'original' has moved.
Sometimes, however, you don't want to move the data—you want to duplicate it. This is where the Clone trait comes in.
Explicit Cloning
The Clone trait provides a method called .clone(). Unlike a move, which simply transfers the pointer to the heap, .clone() performs a "deep copy." It allocates new memory on the heap and copies every piece of data from the original into the new location.
Because this involves heap allocation, it is an explicit action. Rust forces you to write .clone() so that you are always aware of where your program is spending CPU cycles and memory.
let original = String::from("Hello");
let duplicate = original.clone();
println!("Original: {}, Duplicate: {}", original, duplicate);
// This works perfectly! Both variables own their own independent heap data.
When to Use It
You should reach for Clone when you have a piece of heap-allocated data that needs to be used in multiple places independently. By calling .clone(), you break the "single owner" constraint by creating a brand-new, isolated instance of the data that the compiler treats as a completely separate entity.
While Copy types (like integers) are copied automatically and cheaply by the CPU, Clone types represent data that requires effort to replicate. Always use it intentionally to ensure your code remains predictable and performant.
Key Takeaway: The Clone trait allows you to explicitly duplicate heap-allocated data, granting you multiple independent owners at the cost of a new memory allocation.