How to Concatenate Strings in Rust

Created
Modified

Using String.push_str Function

This function actually appends a given string slice onto the end of this `String`. See the following example:

fn main() {
  let mut s1: String = "Hello ".to_owned();
  let s2: &str = "world";

  s1.push_str(s2);
  println!("{}", s1);
}
Hello world

This is efficient as it potentially allows us to reuse the memory allocation.

Using + Operator

This is an implementation of the Add trait that takes a String as the left-hand side and a &str as the right-hand side:

fn main() {
  let s1: String = "Hello ".to_owned();
  let s2: &str = "world";

  // borrow of moved value: `s1`
  // `s1` is moved and can no longer be used here.
  let s = s1 + s2;
  println!("{}", s);

  //  value borrowed here after move
  // println!("{}", s1);

  // let s = s1.clone() + s2;
}
Hello world

If you want to keep using the first String, you can clone it and append to the clone instead.

Using format! Function

What if we wanted to produce a new string, The simplest way is to use format!:

fn main() {
  let s1: String = "Hello ".to_owned();
  let s2: &str = "world";

  let s = format!("{}{}", s1, s2);
  println!("{}", s);
}
Hello world

Using concat! Function

You can use concat!() function to concatenate literals into a static string slice. it really simple. For example,

fn main() {
  let s = concat!("Hello ", "world ", 1);
  println!("{}", s);
}
Hello world 1

Related Tags