Sub topic 5
Growing and changing a String
This chapter assumes you know ownership and borrowing basics, and the difference between &str and String from earlier chapters. Only String can be edited in place. A &str is a read-only view, so every method below belongs to String and needs a mut binding.
Adding text
push appends one char. push_str appends a &str. Mixing them up is a common compile error, because '!' and "!" are different types.
insert and insert_str add text at a byte index instead of the end.
fn main() {
let mut s = String::from("rust");
s.push('y');
s.push_str(" strings");
s.insert(0, '>');
s.insert_str(1, " ");
println!("{s}");
}This prints > rusty strings.
push_str takes a &str. You can pass &other_string because deref coercion turns &String into &str. The += operator does the same job as push_str. extend appends any iterator of char or &str, for example s.extend(['a', 'b']).
Removing and replacing text
The removal methods mirror the additions.
| Method | Effect | Returns |
|---|---|---|
| `pop()` | Removes the last `char` | `Option<char>` |
| `remove(i)` | Removes the `char` starting at byte `i` | `char` |
| `truncate(n)` | Keeps the first `n` bytes | nothing |
| `retain(f)` | Keeps only chars where `f` returns true | nothing |
| `replace_range(r, s)` | Replaces a byte range with `s` | nothing |
| `clear()` | Empties the string | nothing |
fn main() {
let mut s = String::from("héllo, world");
println!("{:?}", s.pop());
println!("{:?}", s.remove(1));
s.truncate(5);
println!("{s}");
s.retain(|c| c != 'l');
println!("{s}");
s.replace_range(0..1, "J");
println!("{s}");
s.clear();
println!("{:?} {}", s, s.is_empty());
}The output is:
Some('d')
'é'
hllo,
ho,
Jo,
"" trueIndex 1 is the start of é, so remove(1) takes out the whole two-byte character. After that, the string is plain ASCII.
How the operations group
Common errors
- Missing
mut.let s = String::from("a"); s.push('b');fails with "cannot borrowsas mutable". Declare it withlet mut s. - Editing a
&str. A literal has nopush_str. Convert it first withString::fromor.to_string(). - Treating
len()as a character count. It returns bytes. Fortruncate, that is what you want. For "the first 5 letters", it is not. - Ignoring
popreturningOption. On an empty string it returnsNone, so handle that case.
Each growth step may reallocate when the buffer is full. A later chapter covers capacity and how to avoid repeated reallocation.
Exercise
A learner writes let mut s = String::from("añb"); s.truncate(2);. Does this compile, and what happens at runtime? What would s.truncate(3) give?
Show answer
It compiles. At runtime it panics, because ñ occupies bytes 1 and 2, so byte 2 is inside it and not a character boundary. s.truncate(3) works and leaves "añ", since byte 3 is the start of b.