'How do I concatenate strings?

How do I concatenate the following combinations of types:

  • str and str
  • String and str
  • String and String


Solution 1:[1]

To concatenate multiple strings into a single string, separated by another character, there are a couple of ways.

The nicest I have seen is using the join method on an array:

fn main() {
    let a = "Hello";
    let b = "world";
    let result = [a, b].join("\n");

    print!("{}", result);
}

Depending on your use case you might also prefer more control:

fn main() {
    let a = "Hello";
    let b = "world";
    let result = format!("{}\n{}", a, b);

    print!("{}", result);
}

There are some more manual ways I have seen, some avoiding one or two allocations here and there. For readability purposes I find the above two to be sufficient.

Solution 2:[2]

Simple ways to concatenate strings in Rust

There are various methods available in Rust to concatenate strings

First method (Using concat!() ):

fn main() {
    println!("{}", concat!("a", "b"))
}

The output of the above code is :

ab


Second method (using push_str() and + operator):

fn main() {
    let mut _a = "a".to_string();
    let _b = "b".to_string();
    let _c = "c".to_string();

    _a.push_str(&_b);

    println!("{}", _a);

    println!("{}", _a + &_c);
}

The output of the above code is:

ab

abc


Third method (Using format!()):

fn main() {
    let mut _a = "a".to_string();
    let _b = "b".to_string();
    let _c = format!("{}{}", _a, _b);

    println!("{}", _c);
}

The output of the above code is :

ab

Check it out and experiment with Rust playground.

Solution 3:[3]

I think that concat method and + should be mentioned here as well:

assert_eq!(
  ("My".to_owned() + " " + "string"),
  ["My", " ", "string"].concat()
);

and there is also concat! macro but only for literals:

let s = concat!("test", 10, 'b', true);
assert_eq!(s, "test10btrue");

Solution 4:[4]

Concatenation by String Interpolation

UPDATE: As of 2021, Dec 28, this is available in Rust 1.58 Beta. You no longer need Rust Nightly build to do String Interpolation. (Leaving remainder of answer unchanged for posterity).

RFC 2795 issued 2019-10-27: Suggests support for implicit arguments to do what many people would know as "string interpolation" -- a way of embedding arguments within a string to concatenate them.

RFC: https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html

Latest issue status can be found here: https://github.com/rust-lang/rust/issues/67984

At the time of this writing (2020-9-24), I believe this feature should be available in the Rust Nightly build.

This will allow you to concatenate via the following shorthand:

format_args!("hello {person}")

It is equivalent to this:

format_args!("hello {person}", person=person)

There is also the "ifmt" crate, which provides its own kind of string interpolation:

https://crates.io/crates/ifmt

Solution 5:[5]

As of Rust 1.58, you can also concatenate two or more variables like this: format!("{a}{b}{c}"). That's basically the same as format!("{}{}{}", a, b, c), but a bit shorter and (arguably) easier to read. Those variables can be String, &str (and also other non-string types for that matter). The result is a String. See this for more.

Solution 6:[6]

By Default in Rust is all about MemoryManage and Owenership and Move, we dont see usually like copy or deep copy hence if you are trying to concatinate strings then left hand side should type String which is growable and should be mutable type, the right hand side can be normal string literal a.k.a type String slices

    fn main (){
            let mut x = String::from("Hello"); // type String
            let y = "World" // type &str
            println!("data printing -------> {}",x+y);



}

official statement from doc, this is pointing to when you are trying using arthmatic + operator enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shepmaster
Solution 2 Matthias Braun
Solution 3 suside
Solution 4
Solution 5 at54321
Solution 6