String::new¶
Level: reference · for working programmers
One line: An empty String that has not allocated — capacity 0, no heap buffer until the first byte goes in.
Stable since 1.0.0. Usable in a const context.
String::new() is free. It sets up three words on the stack — pointer, length, capacity — with a dangling pointer and both counts at zero. The heap is not touched until something is pushed.
That makes it the right default when you do not know the final size, or when the string may well stay empty. When you do know roughly how much text is coming, with_capacity buys the buffer once instead of letting it grow by doubling.
String::new(), String::default() and "".to_string() all give an empty string; only the first two are guaranteed to allocate nothing.
It is const fn, so it can initialize a static.
Example¶
string_new.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let s = String::new();
println!("len {} capacity {}", s.len(), s.capacity());
// The heap is touched on the first push, not before.
let mut grown = String::new();
println!("before len {} capacity {}", grown.len(), grown.capacity());
grown.push('a');
println!("after len {} capacity {}", grown.len(), grown.capacity());
// Three spellings of empty.
println!("{} {}", String::new() == String::default(), String::new() == "".to_string());
// const, so it can initialize a static.
static EMPTY: String = String::new();
println!("{:?} {}", EMPTY, EMPTY.is_empty());
// Building up from nothing is the usual reason to start here.
let mut out = String::new();
for word in ["a", "b", "c"] {
out.push_str(word);
}
println!("{out:?}");
}
Verified output of string_new.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
String::with_capacity— when you know roughly how much text is comingString::is_empty— testing the resultString::push_str— what triggers the first allocationString::capacity— the field this leaves at zero
String::new in the standard library ↗
Po polsku¶
String::new() w ogóle nie dotyka sterty — powstają tylko trzy słowa na stosie (wskaźnik, długość, pojemność), a bufor kupowany jest dopiero przy pierwszym dołożeniu treści. Wynik przykładu mówi to wprost: before len 0 capacity 0, a po dopisaniu jednego znaku od razu capacity 8 — alokator nie wydziela jednego bajtu, tylko od razu z zapasem, i dalej rośnie przez podwajanie. Stąd new() jest właściwym domyślnym wyborem, gdy nie wiadomo, ile tekstu przyjdzie, albo gdy łańcuch znaków ma prawo zostać pusty; jeśli rozmiar znasz z grubsza, with_capacity kupuje bufor raz, zamiast płacić za kilka realokacji po drodze. Ponieważ to const fn, wolno nim zainicjować static — a z trzech zapisów pustego łańcucha (String::new(), String::default(), "".to_string()) tylko dwa pierwsze mają gwarancję, że nie alokują niczego.
Szukaj po polsku: pusty łańcuch bez alokacji · alokacja na stercie · podwajanie pojemności · rust String new vs with_capacity · rust String new does not allocate