Systems and Networking · 14 min · free with an account

Stack and Heap

Lesson preview · about 30%

Where a value lives explains most of what Rust makes you write.

Core idea

The stack holds the handle; the heap holds the data the handle points at.

Start with the idea

A stack frame commonly holds fixed-size local values or handles. Heap allocations support storage whose size or lifetime needs more flexibility and require an owner to release them. Box, Vec, and String are heap values with a small stack handle, which is exactly why moving one is cheap and cloning one is not.

A function call commonly creates a stack frame containing local values or handles whose sizes are known to the compiler. Heap allocation supports values whose storage needs to live independently of a particular stack frame or whose size is chosen at runtime. But ownership and physical location are separate questions. A Vec<T> value holds a pointer, length, and capacity as a small handle; its elements usually live in a heap allocation. Moving the Vec handle transfers ownership of that allocation without copying every element.

Cloning a Vec is different: it creates another allocation and copies or clones elements.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep