Skip to content
Theory · Collections · lesson 5 of 10

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:

Rust
fn main() {
    let s = "Hello";
    s.push_str(", world"); // ✗
    println!("{s}");
}
TEXT
error[E0599]: no method named `push_str` found for reference `&str` in the current scope

The 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:

  • String owns its text: the bytes live on the heap, and the string can grow;
  • &str is a string slice: it only looks at someone else's bytes, such as a literal or a part of a String.

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

Rust
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:

  1. String::from("Hello") gives Hello.
  2. push_str(", ") gives Hello, .
  3. push('w') gives Hello, w.
  4. push_str("orld") gives Hello, 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:

Rust
fn main() {
    let a = String::from("Hello");
    let b = a + ", world";
    println!("{a} {b}"); // ✗
}
TEXT
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 String owns its text and grows, while a &str only looks, so you cannot append to a literal.
  • push_str appends a slice and push one character; both need let mut.
  • format! returns a new String and takes nothing, while + takes the left string.