The stack stores data with a known, fixed size at compile time, while the heap stores data with a size determined at runtime or that needs to be shared. Use the stack for simple, fixed-size types like integers and the heap for dynamic or large data via smart pointers like `Box<T>`.
What Is the Stack vs Heap in Rust?
The stack stores data with a known, fixed size at compile time, while the heap stores data with a size determined at runtime or that needs to be shared. Use the stack for simple, fixed-size types like integers and the heap for dynamic or large data via smart pointers like Box<T>.
fn main() {
let stack_var: i32 = 5; // Stored on the stack
let heap_var = Box::new(vec![1, 2, 3]); // Data stored on the heap
}
Think of the stack as a neat stack of plates where you can only add or remove the top one, used for small, temporary items. The heap is like a large warehouse where you can store big or complex items and access them by a specific address whenever you need them. You use the stack for fast, simple data and the heap when you need to store larger or shared data.