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>`.

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
}