Stack and heap
What you'll learn:
- explain how the stack differs from the heap and where a
Stringkeeps its text; - name the three rules of ownership and the place where Rust frees memory;
- predict what happens to a variable after a move, a
cloneand a copy of a number; - pass a
Stringto a function and get it back.

So far our programs have used numbers, bool, char and text in quotes. The size of each such value is known in advance: an i32 always takes 4 bytes. But programs often work with data whose size is not known in advance: a name the user will type, or a list that grows.
Where do you keep such data, and who cleans it up when it is no longer needed? Rust's answer to this question is ownership, the central idea of the language. Let's start with how memory works.
A computer's memory is a long row of numbered cells, one byte in each. The number of a cell is called its address. A variable takes several cells in a row: an i32 takes four, a bool takes one. A program divides memory into two areas with different rules.
The stack: a pile of trays
Picture a pile of trays in a canteen. When the program calls a function, it puts a new tray on top and places all of that function's variables on it. When the function returns, the top tray is taken off together with everything on it.
This area of memory is called the stack. Space on the stack is set aside and freed automatically, along with the function call, and this is very fast. But the stack has a limit: only values whose size the compiler knows in advance go on a tray. An i32 fits there, but text that may grow does not.
The heap: a storage facility
For data whose size becomes known only while the program runs, there is the heap. Picture a storage facility that rents out units of any size. The program asks the facility for a unit of the right size and gets a key: the address of that unit. The key is small, and it can sit on a tray.
The facility has its own rules:
- finding a free unit takes longer than putting a value on a tray;
- you reach the things in a unit by its address instead of taking them straight from the tray;
- a unit does not disappear when the function returns: it stays taken until someone gives it back.
The last rule is what creates the main difficulty. Someone has to give the unit back, exactly once and only when nobody needs it anymore.
String: text on the heap
In Rust, text that can change and grow is kept in the String type. A string of this type is created from a literal, text in double quotes written right in the code, with String::from:
fn main() {
let age = 30;
let mut name = String::from("Anna");
println!("{name} {}", name.len()); // Anna 4
name.push('!');
println!("{name} {}", name.len()); // Anna! 5
println!("{age}"); // 30
}Let's go through the program line by line:
let age = 30;puts the four bytes of the number30on the tray of the functionmain.String::from("Anna")takes a unit at the facility and puts the four bytes of the textAnnainto it.- The variable
nameon the tray holds a card: the address of the unit, the length of the text and the size of the unit itself. name.len()returns the length, and the first line printsAnna 4.name.push('!')adds a character at the end. If the unit is too small, theStringtakes a bigger unit, moves the text there and updates the card.- The string has grown, and the program prints
Anna! 5, then30.
The card of a String always has the same size: on a 64-bit computer it is 24 bytes, however much text sits in the unit. That is why the card fits on the stack while the text itself does not. The literal "Anna" works differently: its bytes are built into the program itself, and it cannot grow.
Who gives the units back
A unit must be given back exactly once and only after nobody uses it anymore. There are three ways to get this wrong:
- forgetting to give the unit back is a memory leak, and a long-running program gradually takes up all the memory;
- giving the unit back twice confuses the facility's records, and the program breaks;
- opening a unit after it was given back means finding someone else's things in it.
Programming languages solve this problem in different ways.
By hand
In C, the programmer gives memory back by calling free. All three mistakes are possible here, and they cause many security holes in programs.
Garbage collector
Java, Go, Python and C# run a garbage collector. It is a facility service that walks through all the units from time to time and frees the ones nobody holds a key to anymore. Double returns and someone else's things in a unit cannot happen this way, but the walk costs processor time and extra memory, and the program sometimes freezes for a moment.
Ownership
Rust has neither a manual free nor a garbage collector. Every unit has an owner with the only key, and the compiler knows where the owner stops existing. At that place the compiler inserts the return of the unit itself. Everything is checked at compile time, so the running program spends nothing on it.
Here the picture of trays and a facility falls short. The stack and the heap are not two different devices but the same main memory, divided into two areas with different rules.
Interviewers like to ask this: "How does the stack differ from the heap?" The answer:
- the stack holds values of a known size, and space is set aside and freed automatically along with the function call;
- the heap holds data whose size is known only while the program runs, and space there must be given back;
- the stack is faster not because its memory is different: setting aside space there moves the top of the pile, while the heap must search for a free block.
Common mistake
Someone tries to add to a literal as if it were a String:
fn main() {
let mut name = "Anna";
name.push('!'); // ✗
println!("{name}");
}error[E0599]: no method named `push` found for reference `&str` in the current scopeThe compiler finds no push method on a literal. Rust writes the type of a literal as &str, and its bytes are built into the program and cannot grow. Here mut only lets you put a different literal into name. To add to the text, you need a String: let mut name = String::from("Anna");.
Key points
- The stack holds values of a known size, and space there is freed automatically when the function returns.
- The heap holds data whose size is known only while the program runs; space there must be given back exactly once.
- A
Stringkeeps its text on the heap and a card with the address, length and unit size on the stack. - C gives memory back by hand, Java and Go use a garbage collector, and Rust relies on the owner of the value.