A growing String
In the previous lesson a vector lived in a row of lockers and moved to a longer row when it ran out of room. A String is built the same way, only its lockers hold the bytes of text.
But not every string can grow. Let's try to append text to a literal:
fn main() {
let s = "Hello";
s.push_str(", world"); // ✗
println!("{s}");
}error[E0599]: no method named `push_str` found for reference `&str` in the current scopeThe program does not compile: &str has no push_str method. A literal is a string slice, and a slice only looks at someone else's bytes and cannot append anything to them.
String and &str
You have already met both string types:
Stringowns its text: the bytes live on the heap, and the string can grow;&stris a string slice: it only looks at someone else's bytes, such as a literal or a part of aString.
A String is built almost like a vector of bytes: it has the same length, capacity and move on growth. So you append to a String, not to a slice.
Interviewers often ask this: "How is String different from &str?" The answer: a String owns its heap bytes and grows, while a &str only looks at others' bytes.
Appending to the end
fn main() {
let mut s = String::from("Hello");
s.push_str(", ");
s.push('w');
s.push_str("orld");
let line = format!("{s}! {}", s.len());
println!("{line}"); // Hello, world! 12
}push_str and push
push_str appends a string slice to the end, and push appends one char. Both need let mut: they change the string.
In the example the string grows like this:
String::from("Hello")givesHello.push_str(", ")givesHello,.push('w')givesHello, w.push_str("orld")givesHello, world.
Here the vector analogy falls short: a vector's push adds one element, while push_str appends as many bytes as the slice takes at once.
format!
The format! macro builds text by the same rules as println!, but instead of printing it, it returns a new String. In the example it puts in the string s and its length 12, and line gets Hello, world! 12. The string s itself does not change.
Common mistake
You join strings with the + operator and then use the left string again:
fn main() {
let a = String::from("Hello");
let b = a + ", world";
println!("{a} {b}"); // ✗
}error[E0382]: borrow of moved value: `a`The program does not compile. + takes the left string for itself: a has moved into b, and you can no longer print it. The fix is format!, which takes nothing: let b = format!("{a}, world");.
Key points
- A
Stringowns its text and grows, while a&stronly looks, so you cannot append to a literal. push_strappends a slice andpushone character; both needlet mut.format!returns a newStringand takes nothing, while+takes the left string.