Build and modify strings
Quick answer
Use a mutable String to assemble text in stages. push adds one Unicode scalar value, while push_str adds an entire string slice. Neither requires moving the input string slice's owner.
Appending and formatting
String::new() creates an empty owned string. Appending can grow its allocation. format! constructs a new String using a formatting expression, whereas println! displays text. clear() removes the content while retaining the allocated capacity for reuse. Capacity growth is not guaranteed to follow a particular factor.
fn main() { let mut label = String::new(); label.push_str("Room "); label.push('7'); println!("{label}");}Expected stdout (not executed):
Room 7The slice supplies multiple characters; push supplies one.
fn main() { let mut buffer = format!("count={}", 3); println!("{buffer}"); buffer.clear(); buffer.push_str("done"); println!("{buffer}");}Expected stdout (not executed):
count=3doneClearing removes the old text before appending the new message.
Common mistake
Do not pass a string literal to push, which expects a char such as '!'; use push_str for "!".
Try it yourself
Build Item: 4 using String and push_str, then clear the same buffer and build a second label.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Build and modify strings — practice quiz
Choose one answer per question, then review the explanation.
Which macro constructs a String from formatted text without printing it?
What happens to the content and capacity when String::clear is called?
Which call adds one Unicode scalar to a mutable String s?