Skip to content

String::push_str

String methods · Strings

Level: reference · for working programmers

One line: Appends a &str to the end, growing the buffer as needed — the workhorse for building text.

pub fn push_str(&mut self, string: &str)

Stable since 1.0.0.

Takes anything that derefs to &str, so a &String works without ceremony. Returns (), so it does not chain.

Compared with the alternatives:

allocates consumes chains
s.push_str(t) only if it must grow nothing no
s = s + t reuses s's buffer moves s yes
s = format!("{s}{t}") a whole new string nothing yes

In a loop, push_str is the one that does not allocate per iteration. format! in a loop is the classic accidental quadratic — it builds and throws away a fresh String each time.

Pair it with with_capacity when the final size is roughly known, and the whole build costs one allocation.

Example

string_push_str.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let mut s = String::from("hello");
    s.push_str(", world");
    println!("{s:?}");

    // A &String works, via deref.
    let tail = String::from("!");
    s.push_str(&tail);
    println!("{s:?}");

    // One allocation for the whole build.
    let words = ["alpha", "beta", "gamma"];
    let mut out = String::with_capacity(20);
    for (i, w) in words.iter().enumerate() {
        if i > 0 { out.push_str(", "); }
        out.push_str(w);
    }
    println!("{out:?} len {} capacity {}", out.len(), out.capacity());

    // join does the same job for a slice.
    println!("{:?}", words.join(", "));

    // It returns (), so it does not chain.
    let mut t = String::new();
    let unit = t.push_str("x");
    println!("{t:?} returned {unit:?}");
}

Verified output of string_push_str.rs — regenerated by tools/run_examples.py, never hand-typed.

"hello, world"
"hello, world!"
"alpha, beta, gamma" len 18 capacity 20
"alpha, beta, gamma"
"x" returned ()

See also

String::push_str in the standard library ↗

Po polsku

To jest robocze narzędzie do sklejania tekstu: push_str dopisuje &str na koniec, a dzięki dereferencji przyjmuje bez ceremonii również &String. Kto zna Javę, ma gotową analogię — w Ruscie nie ma osobnego StringBuilder, bo String jest builderem, a push_str pełni rolę jego append; klasyczny błąd „konkatenacji w pętli” wygląda tutaj jak s = format!("{s}{t}") powtarzane w każdym obrocie, które za każdym razem alokuje cały nowy łańcuch znaków i daje kwadratowy koszt. Metoda zwraca (), więc nie da się jej łączyć w łańcuszek wywołań — w zamian dostajesz czytelną pętlę, która razem z with_capacity mieści całą budowę w jednej alokacji, jak w przykładzie kończącym się len 18 capacity 20. Jeżeli elementy do sklejenia leżą już w tablicy albo wycinku (slice), krócej wypadnie join(", "), które daje w przykładzie dokładnie ten sam napis.

Szukaj po polsku: sklejanie łańcuchów znaków · konkatenacja w pętli · budowanie tekstu · rust String push_str vs format! · rust join strings with separator