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, suppose 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 methods we can use to concatenate strings in Rust:

  • use join method

    The join function concatenates strings with a specified separator string. The separator can be a space, tab (\t), or a newline (\n).

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

    Output:

    First Second
  • use format macro

    The format function macro formats the string with interpolation syntax. It contains {} syntax with variables separated by commas. Variables are replaced {} and output as a string.

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

    Output:

    First Second
  • use concat macro The concat macro converts multiple strings into a single string. It accepts comma-separated strings of type &'static str.

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

    Output:

    First Second
  • Using the push_str Method The push_str method appends a string to the original string. The 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

    The + operator concatenates two strings and assigns 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

In conclusion, we’ve learned multiple ways to concatenate strings in Rust with examples.