In this lesson, you will learn how to efficiently duplicate small, fixed-size data values directly on the stack without triggering the complex overhead of heap allocation or ownership moves.
The Stack: Fast and Simple
In our study of ownership, you learned that for many types, assigning one variable to another causes a "move." The original variable becomes invalid because Rust wants to ensure there is only one owner of a resource. However, some data is so small and simple—like a single integer—that "moving" it is overkill. Instead, Rust performs Stack-only Data Copying.
When a type implements the Copy trait, the compiler knows that the data exists entirely on the stack and contains no pointers to heap-allocated memory. Because this data is trivial to duplicate (literally just copying a few bytes of memory), Rust doesn't need to invalidate the original variable. It simply copies the bits to a new location.
A Concrete Example
Consider these two snippets:
// A move occurs here because String owns heap memory
let s1 = String::from("Hello");
let s2 = s1; // s1 is now invalid; this is a move
// A copy occurs here because i32 is stack-only
let x = 42;
let y = x; // x is still valid; this is a bitwise copy
In the first case, s1 manages memory on the heap. If we copied it, we would have two variables trying to "own" and clean up the same heap memory, which is a recipe for disaster.
In the second case, x is a simple integer. Its value is stored directly in the stack frame. Copying it is essentially a "memcpy" of 4 bytes. It is lightning-fast and perfectly safe because there is no external resource (like heap memory) attached to it that needs to be "owned."
By relying on stack-only copies for primitive types, Rust keeps your program performant and avoids the cognitive load of tracking ownership for every single number or character in your code.
Key Takeaway: Types that occupy only the stack and contain no heap-pointers can be duplicated via simple bitwise copying, allowing the original variable to remain valid after an assignment.