liveBook · Manning

Capacity

As explained in Refactoring to Rust

Buffer capacity is the number of elements a string buffer can hold before it requires additional allocation.

A Rust `String` has a length—the number of valid elements—and a capacity—the number it can hold before becoming full. Appending past capacity requires reallocation; the standard library does not guarantee a particular growth strategy. section 2.4.1

Listing 2.18 Preallocating strings to aid performance
fn main() {
  let mut x = String::with_capacity(10_000_000);  #1

  for i in 0..10_000_000 {
    x.push('.');
  }

  println!("{}", x.len());
}

Preallocates capacity for a string that will receive ten million appended dots. section 2.4.1

How Refactoring to Rust covers it

How deep it goes
Defines capacity and explains when appending triggers reallocation, but leaves the buffer growth strategy unspecified.
Examples
Demonstrates preallocating a Rust String for ten million appended dots.
What you can do after
Apply it via String::with_capacity to reserve space before appending a known amount of string data.
How it connects
Connects String capacity with string mutation and reallocation.

Also explained in

Compare how 5 books explain capacity →

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.