String::capacity¶
Level: reference · for working programmers
One line: How many bytes the buffer can hold before it must reallocate — always at least len(), and unrelated to the contents.
Stable since 1.0.0. Usable in a const context.
len is what you have written; capacity is what you have paid for. The gap is spare room, and it is why a run of pushes does not reallocate every time.
Three things worth being precise about:
- It is bytes, not characters — same unit as
len. - It is not part of a
String's value. Two strings with the same text and different capacities are==, hash the same, and print the same. Never assert on it in a test. - The exact number is the allocator's business.
with_capacity(n)gives at leastn; growth is roughly doubling but not promised. Depend on the shape, not the digits.
A String::new() has capacity 0 and no heap allocation at all.
Example¶
string_capacity.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let mut s = String::new();
println!("new len {:>2} capacity {:>2}", s.len(), s.capacity());
for word in ["aa", "bbbbbbb", "cccccccccc"] {
s.push_str(word);
println!("+{word:<11} len {:>2} capacity {:>2}", s.len(), s.capacity());
}
// At least what you asked for.
let planned = String::with_capacity(10);
println!("asked 10, got {}", planned.capacity());
// Not part of the value: same text, different capacity, still equal.
let tight = String::from("abc");
let mut roomy = String::with_capacity(64);
roomy.push_str("abc");
println!("equal {} / capacities {} and {}",
tight == roomy, tight.capacity(), roomy.capacity());
// Bytes, not characters.
let wide = "é".repeat(3);
println!("{} chars, len {}", wide.chars().count(), wide.len());
}
Verified output of string_capacity.rs — regenerated by tools/run_examples.py, never hand-typed.
new len 0 capacity 0
+aa len 2 capacity 8
+bbbbbbb len 9 capacity 16
+cccccccccc len 19 capacity 32
asked 10, got 10
equal true / capacities 3 and 64
3 chars, len 6
See also¶
String::with_capacity— buying capacity up frontString::reserve— buying more laterString::shrink_to_fit— giving the spare backString::len— what is actually written
String::capacity in the standard library ↗
Po polsku¶
Dwie liczby i jedno zdanie do zapamiętania: len() mówi, ile już zapisałeś, a capacity() — ile bajtów kupiłeś, czyli ile zmieści się, zanim bufor trzeba będzie przenieść w nowe miejsce. Przykład pokazuje tę drugą w ruchu: String::new() ma pojemność 0 i w ogóle nie sięga po stertę, a kolejne push_str przesuwają ją 0 → 8 → 16 → 32, mniej więcej podwajając. Same cyfry są jednak sprawą alokatora, nie obietnicą — with_capacity(10) gwarantuje co najmniej dziesięć — a pojemność nie należy do wartości łańcucha znaków: w wyniku stoi equal true dla dwóch napisów o tym samym tekście i pojemnościach 3 oraz 64, więc testu sprawdzającego capacity() nie pisz nigdy. Liczone są przy tym bajty, a nie znaki: "é".repeat(3) to trzy znaki i sześć bajtów, więc bufor na polski tekst z ogonkami zapełnia się szybciej, niż podpowiada liczba liter.
Szukaj po polsku: pojemność a długość łańcucha · realokacja bufora · rust String capacity growth · rust with_capacity