1. Three Ways to Clean Up Memory
When a program runs, it places numbers and text on a workbench called memory (RAM). Every time you create data like a string or a list, your program borrows memory from the operating system and must return it when it is no longer needed.
If unused data keeps piling up on the workbench, your computer slows down or the program eventually crashes.
Programming languages handle this cleanup in different ways. In C, the programmer manually writes free() to return memory.
Forgetting to free it causes a memory leak, while accidentally freeing the same space twice triggers a double free bug that can crash the program.
Java and Python rely on an automatic cleaner called a Garbage Collector (GC). This is convenient because programmers do not have to think about returning memory.
However, the program pays a runtime cost whenever the collector pauses to search for unused data.
Rust takes a third approach. It uses neither manual freeing nor a runtime garbage collector.
Instead, the compiler checks a set of Ownership rules while turning your code into an executable, and automatically inserts cleanup code wherever a variable reaches the end of its scope.1
Rust's ownership rules boil down to just three lines:
Every value in Rust has a variable that is its owner.
There can only be one owner for a value at any given time.
When the owner goes out of scope, the value is immediately cleaned up (dropped).
A scope here is the block between { and }. When the variable still holding the string reaches the end of that block, Rust drops the string and returns its heap allocation.
If a value was transferred to another variable before then, the responsibility for cleaning it up moves along with it.
2. Why Does i32 Copy While String Moves?
To see how ownership works in practice, it helps to distinguish two regions of memory: the Stack and the Heap. Even if these terms are new to you, the idea is simple.
They just store data in different ways.
The Stack is like a neat row of fixed-size lockers. Values with a known, fixed size, such as an i32 integer (4 bytes) or a bool (1 byte), go straight onto the top slot without searching for free space.
When a curly-brace scope ends, Rust simply clears slots from the top down in order, which makes the stack very fast.
The Heap is more like a rental warehouse for items whose size can change while the program runs. A String that holds user input or grows as you append text has a length you cannot know ahead of time.
So at runtime, the program asks the warehouse manager for space, and the manager allocates an empty area and hands back a claim ticket (a memory address, or pointer).
An assignment follows the type's rules. i32, f64, and bool all implement Copy. Try let b = a; with one of these values: b's locker gets an exact copy, and a stays usable.2
A String, on the other hand, stores its actual character bytes in the heap warehouse, while its stack locker holds only the claim ticket: the pointer address, current length, and total capacity.
If let s2 = s1; simply copied that claim ticket and left both s1 and s2 owning the same heap warehouse, a serious problem would follow. When the closing } is reached, s2 would empty the warehouse once, and then s1 would try to empty the exact same address a second time. Freeing memory that was already returned and might now hold different data can crash the program or open a severe security hole. This is the double free bug mentioned earlier.
To avoid this, Rust hands the heap claim ticket and ownership over to s2 at let s2 = s1; (a Move), and marks s1 as invalid so it can no longer be used. When the block ends, only s2 cleans up the heap memory, and it happens exactly once.
Let's see the two behaviors side by side in code.
fn main() {
let a = 10;
let b = a; // Copy
println!("a = {}, b = {}", a, b);
let s1 = String::from("iced tea");
let s2 = s1; // Move: ownership of s1 moves to s2
println!("s2 = {}", s2);
// println!("s1 = {}", s1); // Uncommenting causes a compile error: value borrowed here after move
}Output:
a = 10, b = 10
s2 = iced teaLet's walk through the code line by line. In let a = 10; and let b = a;, the value 10 has the default integer type i32.
Because i32 follows the Copy rule, 10 is copied into b, and printing both a and b on the next line works without any issue.
Next, look at String::from("iced tea"). The double colon (::) calls the associated function from on the String type.
When this line runs, "iced tea" is stored in the heap warehouse, and s1 becomes its owner.
Right below that, let s2 = s1; moves ownership to s2. If you remove the comment slashes (//) on the last line and compile, Rust reports an error: value borrowed here after move.
Blocking you from printing a variable can feel strict at first, but it is a safety guard that catches memory bugs before your program ever runs.
3. When You Really Want a Copy: clone()
Sometimes you genuinely want to keep s1 alive while also giving s2 its own separate copy of the string. In that case, you call .clone() explicitly.
Instead of moving the claim ticket, Rust rents a new space in the heap warehouse and duplicates all the character data into it (a deep copy).
Why doesn't Rust just perform a deep copy automatically instead of making you write .clone()?
Copying a few characters is tiny, but silently duplicating a document or array that is tens of megabytes large can suddenly make a program sluggish.
Requiring .clone() makes it visible in the code whenever you are paying for a fresh heap allocation.
fn main() {
let s1 = String::from("iced tea");
let s2 = s1.clone();
println!("Original: {}, Copy: {}", s1, s2);
}Output:
Original: iced tea, Copy: iced teaThe dot (.) in s1.clone() calls a method that belongs to s1. Now there are two separate copies of "iced tea" stored in different spots on the heap, with s1 and s2 each owning their own.
When main ends, s1 and s2 each clean up only their own buffer once, so there is no risk of a double free.
4. Passing a Value to a Function Also Moves Ownership
Passing a variable as an argument to a function follows the exact same rules as let assignment. Passing a Copy type like i32 copies the value, so the original variable stays usable.
Passing a String directly, however, moves ownership into the function, and the string is freed as soon as that function ends.
fn print_length(item: String) {
println!("Item name length: {}", item.len());
} // item goes out of scope and its string is dropped.
fn main() {
let item = String::from("iced tea");
print_length(item);
// println!("{}", item); // Uncommenting this tries to use a moved value.
}Output:
Item name length: 8let item = String::from("iced tea"); gives main ownership of the item name. The call to print_length(item); hands ownership to the function's parameter item: String.
item.len() counts bytes. The name iced tea takes eight bytes, including the space. At the closing brace of print_length, the parameter goes out of scope and Rust drops its string buffer.
Uncomment the last println! to try printing item again in main. The compiler rejects it because the call already moved the value out.
Calling print_length(item.clone()) every time would waste memory on unnecessary copies.
What we need is a way to keep ownership ourselves while lending a function temporary permission to read the value. That is exactly what Borrowing (&) solves, and we will cover it next in Part 5.
Footnotes
- The Rust Programming Language, Ch. 4.1 What Is Ownership? https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html β©
- Rust Standard Library, std::marker::Copy: https://doc.rust-lang.org/std/marker/trait.Copy.html β©