Sub topic 5
Growing and changing a String
This chapter assumes you know basic Rust syntax, ownership and borrowing, and how Option works. It also assumes you have read the earlier chapters on &str versus String and on UTF-8. You will learn how to add to, remove from, and rewrite a String in place. You will also learn which edits can panic and which methods return a new value instead of changing the original.
Why only String can change
A &str is a borrowed view into text that someone else owns. You can't resize it, because you don't own the memory behind it. A String owns a heap buffer that can grow, so it is the type you edit.
Editing needs two things:
- A
mutbinding, or a&mut Stringparameter. - A method that works on the owned buffer.
Leaving out mut is the most common mistake. The compiler reports cannot borrow s as mutable, as it is not declared as mutable, and the fix is to write let mut s.
Adding text
push appends one char. push_str appends a &str. The argument types are strict: push("!") fails because "!" is a &str, and push_str('!') fails because '!' is a char.
insert and insert_str add text at a byte index instead of the end.
fn main() {
let mut s = String::from("rust");
s.push('!');
s.push_str(" fun");
s.insert(0, '>');
s.insert_str(1, "> ");
println!("{s}");
}This prints >> rust! fun. The calls return (), so you can't chain them.
Inserting at the front moves every existing byte to make room. That costs time proportional to the string length. Appending is usually cheap, and inserting near the start in a loop gets slow on long strings.
Byte indexes and panics
The index you give to insert, insert_str, remove, truncate, drain, and replace_range is a byte offset, not a character position. The offset must fall on a char boundary. If it lands inside a multi-byte character, the method panics.
Use is_char_boundary when the index comes from outside your control.
fn main() {
let mut s = String::from("é!");
let idx = 1;
if s.is_char_boundary(idx) {
s.insert(idx, '-');
} else {
println!("index {idx} is inside a character");
}
println!("{s}");
}The é takes bytes 0 and 1, so index 1 is not a boundary. The program prints the warning message, then é!.
Indexes found by find or char_indices are always valid boundaries. Arbitrary arithmetic like len() / 2 is not.
Removing text
| Method | What it does | Returns |
|---|---|---|
| `pop()` | Removes the last `char` | `Option<char>` |
| `remove(i)` | Removes the `char` starting at byte `i` | `char` (panics if out of range or off a boundary) |
| `truncate(n)` | Keeps the first `n` bytes | `()` (panics off a boundary) |
| `clear()` | Removes everything, keeps the buffer | `()` |
| `retain(f)` | Keeps only `char`s for which `f` returns true | `()` |
| `drain(range)` | Removes a byte range and yields it | iterator of `char` |
| `replace_range(range, s)` | Swaps a byte range for new text | `()` |
pop returns an Option because the string may be empty. remove has no such protection: remove(0) on an empty string panics.
fn main() {
let mut s = String::from("héllo, world");
let last = s.pop();
let first = s.remove(0);
println!("{last:?} {first}");
println!("{s}");
s.truncate(4);
println!("{s}");
s.clear();
println!("{:?} {}", s, s.is_empty());
}The output is:
Some('d') h
éllo, worl
éll
"" truetruncate(4) works because é takes two bytes and the two ls take one each, so byte 4 is a boundary. truncate never grows a string. If n is larger than the length, nothing happens.
clear sets the length to zero but keeps the allocated memory. This makes it a good choice when you reuse one String as a scratch buffer inside a loop.
Filtering and range edits
retain takes a closure over each char. drain removes a range and hands the removed characters back through an iterator. replace_range overwrites a range with new text, and the new text can be longer or shorter than the old.
fn main() {
let mut s = String::from("a1b2c3");
s.retain(|c| c.is_alphabetic());
println!("{s}");
let mut t = String::from("hello big world");
let removed: String = t.drain(5..9).collect();
println!("{t:?} {removed:?}");
t.replace_range(0..5, "HOWDY");
println!("{t}");
}This prints abc, then "hello world" " big", then HOWDY world. The range 5..9 covers the space and big.
If you drop the iterator from drain without consuming it, the range is still removed. The removal happens when the iterator is dropped.
Extending from many pieces
extend appends everything from an iterator. String accepts iterators of char, &char, &str, and String.
fn main() {
let mut s = String::new();
s.extend(['a', 'b']);
s.extend(["cd", "ef"]);
s += "gh";
println!("{s}");
}This prints abcdefgh. The += operator is the same as push_str. The next chapter covers +, format!, and join, which build new strings from parts.
Mutating through a function
To edit a caller's string, take &mut String. Use &mut String only when the function really changes the buffer. If it only reads, take &str.
fn add_suffix(s: &mut String, suffix: &str) {
if !s.ends_with(suffix) {
s.push_str(suffix);
}
}
fn main() {
let mut name = String::from("report");
add_suffix(&mut name, ".txt");
add_suffix(&mut name, ".txt");
println!("{name}");
}The second call does nothing, so the output is report.txt.
Methods that look like edits but are not
Many methods return a new String and leave the original alone. Forgetting to use the result is a common bug.
fn main() {
let mut s = String::from("Hello");
let upper = s.to_uppercase();
println!("{s} {upper}");
s.make_ascii_uppercase();
println!("{s}");
}The output is Hello HELLO, then HELLO. to_uppercase, to_lowercase, replace, and trim all return new values. trim returns a &str view, not a new String. The in-place versions exist only for ASCII: make_ascii_uppercase and make_ascii_lowercase change letters a to z and leave other characters, such as é, as they are. Changing case across all of Unicode can change the byte length, for example ß becomes SS. That is why to_uppercase allocates a new string.
To apply a non-in-place result to the same variable, assign it back:
fn main() {
let mut s = String::from("a-b-c");
s = s.replace('-', "+");
println!("{s}");
}This prints a+b+c.
Borrows and edits
A slice or &str taken from a String borrows it. While that borrow is alive, the compiler won't let you call any method that needs &mut self. Appending might reallocate the buffer, which would leave the slice pointing at freed memory. The borrow checker prevents that.
If you write let first = &s[0..2];, then call s.push_str(" world"), then use first, the compiler reports error E0502. Fix it by ending the borrow earlier or by copying the slice into its own String:
fn main() {
let mut s = String::from("hello");
let first = s[0..2].to_string();
s.push_str(" world");
println!("{first} {s}");
}This prints he hello world.
Choosing an operation
Common errors
- Missing
mut. The binding or parameter must be mutable. - Wrong argument type.
pushwantschar,push_strwants&str. - Off-boundary index.
insert,remove,truncate,drain, andreplace_rangepanic when the byte index splits a character. - Ignored return value.
s.replace(..)ors.to_uppercase()on its own line does nothing useful. The compiler may warn about an unused result. - Editing while borrowed. Hold a slice, and the string can't be changed until you stop using the slice.
- Slow loops. Repeated
insert(0, ..)on a long string moves all the bytes each time. Build the pieces in order, or collect and reverse them.
Exercise
What happens when you run let mut s = String::from("héllo"); s.truncate(2);, and how can you avoid the problem?
Show answer
It panics. The é occupies bytes 1 and 2, so byte offset 2 is in the middle of the character and is not a char boundary. Check s.is_char_boundary(2) before calling truncate, or get the offset from char_indices so it is always a boundary. s.truncate(3) works and leaves "hé".
Exercise
You have let mut s = String::from("a b c"); and want to remove every space in place without allocating a new String. Which method do you use, and what is the result?
Show answer
Use s.retain(|c| c != ' ');. It keeps only the characters for which the closure returns true, so s becomes "abc". Calling s.replace(" ", "") would not change s. It would return a new String that you would have to assign back.