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.
let mut s = String::from("ab"); s.push('c'); // "abc" s.push_str("de"); // "abcde" s.insert(0, '>'); // ">abcde"
Try it
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.
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
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_strtakes&str, so pass&other_stringto append anotherString(deref coercion handles it). It never consumes its argument.- Appending is amortized O(1) per byte because capacity doubles when exhausted.
insertandinsert_strare O(n): everything after the position shifts. Inserting at the front in a loop is quadratic; build the pieces in order, or use aVecof pieces and join. a + &bconsumesaand reuses its buffer, so it is cheap, buta + &b + &cin one expression works only because each+returns aString. The left-most operand must be an ownedString, not a&str("a" + "b"does not compile).- Prefer
format!orwrite!for mixed content.format!("{a}-{b}")is clearer than a chain of+, andwrite!into an existingStringavoids an extra allocation.write!needsuse std::fmt::Write, and its result is afmt::Resultthat cannot actually fail forString, so.unwrap()is fine. pushadds onechar, not one "letter": a visible character built from several scalar values (like some emoji) takes several calls.extendaccepts many item types, which makes it a handy alternative to a loop ofpush_str.- Mutation requires
muton the binding or a&mut Stringreference.