In this lesson, you will learn how to distinguish between a fast, bitwise copy of stack data and the comprehensive, resource-heavy process of duplicating heap-allocated structures.
The Shallow Copy (Copying the Stack)
In Rust, primitive types like i32, bool, or char have a fixed size known at compile time and live entirely on the stack. When you assign one variable to another, Rust performs a "shallow copy." It simply copies the bits from one memory location to another.
let x = 5;
let y = x; // Shallow copy: x and y are two independent integers on the stack
Because these types implement the Copy trait, this operation is instantaneous and perfectly safe. There is no confusion about ownership here because there is nothing stored on the heap to "clean up."
The Deep Copy (Cloning the Heap)
When you move into complex types like String or Vec, the situation changes. Remember from our lesson on the stack and heap that these types store a small "pointer" on the stack, but the actual data lives on the heap.
If we performed a shallow copy on a String, we would copy the pointer, the length, and the capacity to a new variable. Now, both variables would point to the same memory address on the heap. This would violate Rust’s ownership rules, as two variables would be responsible for dropping the same heap memory.
To create a truly independent duplicate of heap data, we perform a "deep copy" using the .clone() method:
let s1 = String::from("hello");
let s2 = s1.clone(); // Deep copy: allocates new memory on the heap for "hello"
// s1 and s2 are now entirely independent
A deep copy performs an explicit allocation on the heap and copies every individual byte of the underlying data. While this ensures both variables own their own data, it is significantly more expensive in terms of CPU and memory usage than a shallow copy. Rust forces you to call .clone() explicitly so you are always aware of when you are triggering these potentially costly operations.
Key Takeaway: Shallow copies are fast, stack-based bitwise operations, while deep copies are manual, resource-intensive operations that allocate new heap memory to ensure independence.