liveBook · Manning

Immutable string

As explained in Refactoring to Rust

An immutable string is a string value whose character data cannot be modified after the value is created.

An immutable string cannot have its character data edited after creation. Operations that appear to change it, such as +=, instead create a new string containing the requested content. section 2.4.1

This behavior can become expensive when repeatedly extending a string. Adding one character in a ten-million-iteration loop creates ten million allocations and copies nearly all existing data each time. section 2.4.1

Repeated concatenation

The Python loop starts with an empty string, appends a dot ten million times, and prints the length. Its externally visible result is simple, but its immutable-string behavior repeatedly copies the accumulated value. section 2.4.1

Rust contrasts this with a mutable, growable String whose heap buffer has a length and capacity. Appending usually changes the existing buffer; allocation and copying occur when the new length exceeds capacity. section 2.4.1

How Refactoring to Rust covers it

How deep it goes
Explains allocation, copying, reallocation, buffer length, and capacity, but stops short of broader string representation details.
Examples
Uses a Python ten-million-dot loop, Rust push loops, and capacity preallocation to compare construction costs.
What it assumes
Assumes familiarity with ordinary string concatenation while teaching mutability and allocation behavior from the beginning.
What you can do after
Evaluate repeated string construction by identifying unnecessary allocations and comparing it with mutable-buffer construction.
How it connects
Connects immutability with mutability, string concatenation, heap allocation, reallocation, and Rust String values.

Related concepts

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