6.4 The String Type and Memory Details
Understanding how String works internally helps clarify ownership and borrowing.
- Stack vs. Heap: While the
Stringmetadata lives where theStringvariable is declared (stack for local variables, potentially heap if part of another structure), the actual character data resides on the heap. This dynamic allocation is whyStringisn’tCopy. StringStructure: AStringconsists of three parts stored together (often on the stack):- A pointer to a buffer on the heap containing the actual UTF-8 encoded character data.
- A length: The number of bytes currently used by the string data.
- A capacity: The total number of bytes allocated in the heap buffer.
- Growth: When you append to a
Stringand its length exceeds its capacity, Rust reallocates a larger buffer on the heap (often doubling the capacity), copies the old data over, updates the pointer, length, and capacity, and frees the old buffer. - Dropping: When a
Stringowner goes out of scope, itsdropimplementation frees the heap buffer.