Best way to do string concatenation in 2019 (Status quo)

Hi everyone,

I am a newbie in rust with 3-days experience...

Yes I know, you will say again this subject but I read many things about string concatenation:

But now in 2019, what is the best and pragmatic way to achieve this simple operation. What is recommended by the language designers?

It is foreseen in the future to make it more user-friendly... I think about thing like "string interpolation" like in Kotlin, Scala or Ruby?

Thank you in advance :slight_smile:

String interpolation via format! is what I typically use: https://github.com/rust-unofficial/patterns/blob/4ab5a61eb50359bcc22a43ebcb938dc4fce67163/idioms/concat-format.md

If a benchmark later reveals it to be a bottleneck (perhaps because of the required allocation), then fix it within the constraints of your specific problem.

In many cases, needing to use format! is unnecessary. For example, if you're using println! to print something to stdout, you don't need to do println!("{}", format!("{}{}", foo, bar)), but rather, println!("{}{}", foo, bar); is sufficient.

I'm not aware of any specific plans to add new string interpolation facilities.

3 Likes

If you have a few strings to join, use any method you like. They will all be fine. format!("{}{}", a, b) is usually convenient. a + b works too if a is a String (you will need to learn the ownership difference between String and &str).

If you have a million strings, then start with this:

let mut s = String::with_capacity(estimated_total_length_of_the_string);

and then you can append to s in a loop, or use s.extend(…) to append from an iterator, etc.

1 Like

Also, if you have many strings, you may want to have a look at this thing (I'm not sure how close to your problem it is):

1 Like

Another one for the list:

    let a = "abc";
    let b = "def";
    let c = "ghi";
    let x = [a, b, c].concat();
    println!("{:?}", x);

Which automatically does the capacity calculation that @kornel mentioned.

11 Likes

@scottmcm you mean that "join" is better for every case? or that is a better way to do the capacity calculation?

I think it's an elegant & efficient way if you happen to have a bunch of &strs already. Up to you whether it's "better"; it does the same things as appending to an appropriate-capacity String manually.

1 Like