6.4 The String
Type and Memory Details
Understanding how String
works internally helps clarify ownership and borrowing.
- Stack vs. Heap: While the
String
metadata lives where theString
variable 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 whyString
isn’tCopy
. String
Structure: AString
consists 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
String
and 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
String
owner goes out of scope, itsdrop
implementation frees the heap buffer.