Concatenating strings
- Rust course
- Beginner
- Lesson 21/115
- 4 min
Concatenate strings with push_str and the + operator.
Concatenating Strings
Ways to append to a String:
let mut s = String::from("Merhaba");
s.push_str(", "); // appends a &str
s.push('R'); // appends one char
s += "ust"; // appends a &str
println!("{s}"); // Merhaba, RustThe + operator takes ownership of the String on the left: after let c = a + &b;, a can't be used, while b was only borrowed and stays usable.
Joining many pieces
When joining many pieces, chains of + become unreadable. format! takes ownership of none of its arguments and is the most readable option; for slices there are concat and join:
let ad = "Ada";
let soyad = "Lovelace";
let tam = format!("{ad} {soyad}");
let liste = ["a", "b", "c"].join(", "); // "a, b, c"
let bitisik = ["x", "y"].concat(); // "xy"Practice Build a greeting
Start with let mut s = String::from("Merhaba");. Call push_str(", "), push_str("Rust") and push('!'); then do let t = s + " 🦀"; and print t.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let mut s = String::from("Merhaba");
s.push_str(", ");
s.push_str("Rust");
s.push('!');
let t = s + " 🦀";
println!("{}", t);
}Expected output
Merhaba, Rust! 🦀
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why doesn't <code>let a = String::from("x"); let b = String::from("y"); let c = a + b;</code> compile?
- The right side must be a &str; write a + &b Correct answer
- a is immutable
- Strings can't be added
- It compiles
Explanation: The + operation has the signature fn add(self, s: &str); that's why the second operand must be a reference.
2 Append one character
let mut s = String::from("ok");
s.____('!');
let mut s = String::from("ok");
s.push('!');
Explanation: push appends a single char; push_str appends a &str.
3 Method and argument
| Term | Meaning |
|---|---|
push_str |
&str |
push |
char |
a + &b |
Takes ownership of a |
format! |
Takes no ownership |