CodeBlanks Logo Icon CodeBlanks

Concatenating strings

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

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

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
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

Question
let mut s = String::from("ok");
s.____('!');
Answer
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

All lessons in Beginner