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 the String 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 why String isn’t Copy.
  • String Structure: A String consists of three parts stored together (often on the stack):
    1. A pointer to a buffer on the heap containing the actual UTF-8 encoded character data.
    2. A length: The number of bytes currently used by the string data.
    3. 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, its drop implementation frees the heap buffer.