In this lesson, you will learn the fundamental difference between the Stack and the Heap, and why Rust requires you to understand where your data lives.
The Stack: Predictable and Fast
The Stack is like a neatly organized pile of cafeteria trays. It works on a "Last-In, First-Out" (LIFO) basis. When you declare a variable with a fixed size—like an i32 integer or a fixed-size array—Rust places it directly on the stack.
Because the computer knows exactly how much memory these items need at compile-time, accessing them is incredibly fast. The pointer simply moves up or down the stack to "push" or "pop" data. However, everything on the stack must have a size known ahead of time.
The Heap: Flexible but Complex
Sometimes, your program doesn't know how much data it will handle until it is actually running (like reading a user-provided text file or a dynamic list). For this, we use the Heap.
When you put data on the heap, you are essentially asking the operating system for a chunk of space. The OS finds an empty spot, marks it as "in use," and returns a pointer (a memory address) to that location. You store that pointer on the stack, but the actual data lives elsewhere.
fn main() {
let x = 10; // Stored on the Stack (Size is known)
// String is stored on the Heap because it can grow
// 's' (on the stack) holds a pointer to the heap memory
let s = String::from("Hello, Rust!");
}
Key Differences
- Speed: Stack access is faster because the computer doesn't have to search for space; it just moves a pointer.
- Flexibility: The heap allows data to grow or shrink dynamically during execution, which the stack cannot do.
- Management: Rust manages the stack automatically when a function ends. For the heap, Rust uses its unique "ownership" rules (which we will explore later) to clean up memory once it is no longer needed, preventing the memory leaks common in other languages.
Key Takeaway: The stack is for fixed-size, compile-time data; the heap is for dynamic, run-time data that needs to grow or persist independently of a function's scope.