String::clear¶
Level: reference · for working programmers
One line: Empties the string but keeps the buffer — len() becomes 0, capacity() does not change.
Stable since 1.0.0.
That retention is the whole point: it is what makes a reusable buffer work. Clearing between loop iterations costs nothing and the next iteration writes into memory that is already allocated, so a read-process-clear loop allocates once rather than once per item.
Replacing the binding with String::new() looks equivalent and is not — it drops the buffer and the next push allocates again.
To actually release the memory, follow with shrink_to_fit, or shrink_to to keep a working floor.
Equivalent to truncate(0).
Example¶
string_clear.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let mut s = String::with_capacity(32);
s.push_str("hello");
println!("before len {} capacity {}", s.len(), s.capacity());
s.clear();
println!("after len {} capacity {}", s.len(), s.capacity());
// The reusable-buffer pattern: one allocation for the whole loop.
let mut buf = String::new();
for line in ["alpha", "beta", "gamma"] {
buf.clear();
buf.push_str(line);
buf.push('!');
println!("{buf:?} capacity {}", buf.capacity());
}
// Reassigning instead throws the buffer away.
let mut fresh = String::with_capacity(32);
fresh.push_str("x");
fresh = String::new();
println!("reassigned capacity {}", fresh.capacity());
// Releasing the memory for real.
let mut done = String::with_capacity(32);
done.push_str("x");
done.clear();
done.shrink_to_fit();
println!("cleared and shrunk: capacity {}", done.capacity());
}
Verified output of string_clear.rs — regenerated by tools/run_examples.py, never hand-typed.
before len 5 capacity 32
after len 0 capacity 32
"alpha!" capacity 8
"beta!" capacity 8
"gamma!" capacity 8
reassigned capacity 0
cleared and shrunk: capacity 0
See also¶
String::truncate— the general formString::shrink_to_fit— releasing the retained bufferString::is_empty— the test afterwardsString::capacity— what this deliberately preserves
String::clear in the standard library ↗
Po polsku¶
clear() opróżnia tekst, ale zostawia bufor — w wyniku widać before len 5 capacity 32, a zaraz potem after len 0 capacity 32. To nie jest szczegół implementacyjny, tylko cały sens metody: pętla, która w każdym obrocie czyści i zapisuje ten sam String, alokuje raz zamiast raz na element, i dlatego pojemność 8 utrzymuje się przez wszystkie trzy przebiegi przykładu. Podmiana zmiennej na String::new() wygląda na to samo, a nie jest — stary bufor zostaje wypuszczony i kolejne push znowu alokuje, co widać jako reassigned capacity 0. Najczęściej spotkasz ten wzorzec przy czytaniu pliku wiersz po wierszu: BufRead::read_line dopisuje do podanego bufora, więc clear() na początku obrotu jest tam koniecznością, a nie optymalizacją; gdy pamięć ma naprawdę wrócić do systemu, dołóż shrink_to_fit().
Szukaj po polsku: ponowne użycie bufora · czyszczenie łańcucha znaków · rust String clear vs new · rust read_line reuse buffer