String is a growable, owned text buffer. push_str adds text and push adds one character.

Program

Play the program to build a word one piece at a time.

strings.rs
Replay: real traced execution (multi-file project)
fn main() {
    let mut sentence = String::new();
    sentence.push_str("Rust");
    sentence.push('!');
    println!("{sentence} ({})", sentence.len());
}
  1. sentence ← ""

    1fn main() {2    let mut sentenc→ ""e = String::new();3    sentence.push_str("Rust");4    sentence.push('!');5    println!("{sentence} ({})", sentence.len());6}
    outputRust! (5)

Follow the String

  1. sentence starts empty.
  2. push_str("Rust") changes it to Rust.
  3. push('!') changes it to Rust!.
  4. sentence.len() is 5.
  5. The program prints Rust! (5). | step | sentence | length | | --- | --- | --- | | start | empty | 0 | | after push_str | Rust | 4 | | after push | Rust! | 5 |
String::new `String::new()` starts an empty owned string.
push_str `push_str` appends a string slice.
push `push` appends a single `char`.

Exercise: strings.rs

Reproduce Rust! (5), then identify which step changes the length from 4 to 5.