Collections
Strings
Building Text
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());
}
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
sentencestarts empty.push_str("Rust")changes it toRust.push('!')changes it toRust!.sentence.len()is5.- The program prints
Rust! (5). | step | sentence | length | | --- | --- | --- | | start | empty | 0 | | afterpush_str|Rust| 4 | | afterpush|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.