liveBook · Manning

Stack

As explained in Learn Rust in a Month of Lunches

The stack is a memory region that stores values with a known size and releases them in last-in, first-out order as execution leaves scopes or functions.

A stack is a fast memory region where values are placed one after another and released in last-in, first-out order. When a function finishes, its most recently added values are removed first. section 2.1

The core rules are simple:

  • The stack works well for values whose exact size is known at compile time, such as an i32, which always occupies 4 bytes. section 2.1
  • Values are removed from the top first, much like dishes being taken from a stack. section 2.1
  • When data has an unknown size, the data can live on the heap while a fixed-size pointer to it remains on the stack. section 2.1
  • Small embedded devices may provide only stack memory because they have no operating system to request heap memory. section 2.1

A dish stack in memory

Imagine placing a variable on top of the previous variable. When the function ends, the newest variable comes off first, then the one beneath it. This arrangement is fast because the values sit next to one another and their sizes are known. section 2.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines speed, last-in-first-out release, compile-time sizing, heap pointers, and embedded limitations without detailing implementation internals.
Examples
Uses a stack of dishes, an i32 value, heap data with a stack pointer, and a small embedded device.
What you can do after
Understand why some Rust values use the stack and how pointers connect stack locations to heap data.
How it connects
Connects the stack with the heap, pointers, references, variables, functions, and ownership.

Also explained in

Compare how 14 books explain stack →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.