How to concatenate a Strings in Rust example

In this example, You’ll find multiple ways to concatenate a string in rust with examples.

For example, you have two strings declared in Rust.

    let first = "First";
    let second = "Second";

After appending the strings, the Result is First Second

How to append a string in Rust

There are multiple ways we can use to concatenate Strings in Rust

  • use join method

join function concatenates with separator string. The separator can be space, tab(\t), or our new line (\n).

fn main() {
    let first = "First";
    let second = "Second";
    let output = [first, second].join(" ");
    print!("{}", output);
}

Output:

First Second
  • use format macro

format function macro format the string with interpolation syntax

It contains {} syntax with variables separated by comma

Variables are replaced {} and output a string

fn main() {
    let first = "First";
    let second = "Second";
    let output = format!("{} {}", first, second);
    print!("{}", output);
}

Output:

First Second
  • use concat macro concat macro converts multiple strings into a single string. It accepts comma separate strings of type &'static str
fn main() {
    let output = concat!("First", " ", "Second");
    print!("{}", output);
}

Output:

First Second
  • push_str method push_str is a method used to append a string to the original string. Original String is modified and declared with the mut keyword

Here is an example program for push_str append strings

fn main() {
    let mut first = "First".to_string();
    let second = "Second".to_string();
    first.push_str(&second);
    println!("{}", first);
}

Output:

FirstSecond
  • use + operator

  • operator concatenate two strings and assigned the result to a new variable. The original string is not modified, so mut is not required.

fn main() {
    let first = "First".to_string();
    let second = "Second".to_string();
    let result = first + &second;
    println!("{}", result);
}

Output:

FirstSecond

Conclusion

To summarize, Learned multiple ways to append strings in Rust with examples.