192 words
1 minutes
250103_string_format_push_str_concat_join_push

link#


✅ Summary#

MethodMoves?Mutable?Recommended
+yesnosometimes
format!nono⭐ best
push_strnoyes⭐ best for struct
pushnoyeschar only
concat()nonoslice
join()nonoslice with separator

There are several ways to concatenate strings#

  • In Rust, there are several ways to concatenate strings, and each one works a little differently because of ownership rules.

  • Here are the main ways with clear examples.

1. Using + operator (moves left side)#

fn main() {
    let a = String::from("young");
    let b = String::from("ha");

    let c = a + &b;

    println!("{c}");
}
  • Output
youngha
IMPORTANT

a is moved

let c = a + &b;
  • is actually:
String::add(a, &b)
  • So after this, a cannot be used.

2. Using format! (safe, no move)#

  • Best general method.
fn main() {
    let a = String::from("young");
    let b = String::from("ha");

    let c = format!("{}{}", a, b);

    println!("{c}");
    println!("{a}");
    println!("{b}");
}
  • Output
youngha
young
ha
  • ✔ does not move
  • ✔ easiest
  • ✔ recommended

3. Using push_str (modify existing string)#

  • Best when mutating struct / variable.
fn main() {
    let mut a = String::from("young");

    a.push_str("ha");

    println!("{a}");
}
  • Output
youngha

4. Using push (single char)#

fn main() {
    let mut a = String::from("young");

    a.push('!');

    println!("{a}");
}
  • Output
young!

5. Using concat() (slice of strings)#

fn main() {
    let a = "young";
    let b = "ha";
    let c = "kim";

    let s = [a, b, c].concat();

    println!("{s}");
}
  • Output
younghakim

6. Using join()#

fn main() {
    let parts = ["young", "ha", "kim"];

    let s = parts.join("-");

    println!("{s}");
}
  • Output
young-ha-kim
250103_string_format_push_str_concat_join_push
https://younghakim7.github.io/blog/posts/250103_string_format_push_str_concat_join_push/
Author
YoungHa
Published at
2025-01-03