Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Strings and Text

String push, push_str and insert

Reference for appending and inserting text in a Rust String: push, push_str, insert, insert_str, the + and += operators, extend and write!.

A String grows through a small set of methods. push appends one char, push_str appends a &str, and insert and insert_str put a character or string at a byte position in the middle. The += operator is shorthand for push_str, while + builds a new string by taking ownership of the left side and appending the right.

For many pieces, extend appends from an iterator, and write! appends formatted text without creating a temporary string.

Rust
let mut s = String::from("ab");
s.push('c');          // "abc"
s.push_str("de");     // "abcde"
s.insert(0, '>');     // ">abcde"

Try it

Rust Appending and inserting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust The + operator and write!

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
impl String {
    pub fn push(&mut self, ch: char);
    pub fn push_str(&mut self, string: &str);
    pub fn insert(&mut self, idx: usize, ch: char);
    pub fn insert_str(&mut self, idx: usize, string: &str);
}
impl Add<&str> for String { type Output = String; /* ... */ }
impl AddAssign<&str> for String { /* ... */ }
impl Extend<char> for String { /* also &char, &str, String, Cow<str> */ }
Name Description
ch The char to add. Encoded as 1 to 4 UTF-8 bytes.
string The text to add; any &str, including &String.
idx A byte offset where the new text starts. Must be <= len() and on a char boundary.

Returns: nothing (()); the string is changed in place. + returns the extended String.

Panics: insert and insert_str panic if idx is greater than the length or is not on a character boundary. They never fail for valid positions, but may reallocate.

Usage notes

  • push_str takes &str, so pass &other_string to append another String (deref coercion handles it). It never consumes its argument.
  • Appending is amortized O(1) per byte because capacity doubles when exhausted. insert and insert_str are O(n): everything after the position shifts. Inserting at the front in a loop is quadratic; build the pieces in order, or use a Vec of pieces and join.
  • a + &b consumes a and reuses its buffer, so it is cheap, but a + &b + &c in one expression works only because each + returns a String. The left-most operand must be an owned String, not a &str ("a" + "b" does not compile).
  • Prefer format! or write! for mixed content. format!("{a}-{b}") is clearer than a chain of +, and write! into an existing String avoids an extra allocation. write! needs use std::fmt::Write, and its result is a fmt::Result that cannot actually fail for String, so .unwrap() is fine.
  • push adds one char, not one "letter": a visible character built from several scalar values (like some emoji) takes several calls.
  • extend accepts many item types, which makes it a handy alternative to a loop of push_str.
  • Mutation requires mut on the binding or a &mut String reference.