Values and memory: stack and heap concepts
Quick answer
Rust manages memory using ownership. A useful mental model distinguishes the stack, which typically holds function call state and fixed-size local values, from the heap, where dynamically allocated data can live.
Representation is not placement
A String owns a UTF-8 byte buffer. Conceptually, a local String holds metadata (pointer, length, capacity) referring to the allocation. A small integer needs no separate allocation. These are models, not guaranteed physical stack locations: a compiler can optimize values into registers or eliminate them. Length is bytes, while capacity measures allocated byte storage available to the string.
fn main() { let count: u32 = 12; println!("{} bytes", std::mem::size_of_val(&count));}Expected stdout (not executed):
4 bytesThe ampersand passes a shared reference; u32 has a fixed four-byte size.
fn main() { let text = String::from("Rust"); println!("length: {}", text.len()); println!("enough capacity: {}", text.capacity() >= text.len());}Expected stdout (not executed):
length: 4enough capacity: trueThe four ASCII bytes form the content; capacity can be greater than length.
Common mistake
Do not assume every local variable physically resides on the stack, or that a String's value is only its characters.
Try it yourself
Draw a conceptual String with its length and capacity pointing to a four-byte buffer. Explain what happens when the owner goes out of scope.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Values and memory: stack and heap concepts — practice quiz
Choose one answer per question, then review the explanation.
Which description of a String's capacity is accurate?
Must every local integer physically reside on the stack?
What does String metadata conceptually describe?