Joining str: many ways


let a = "abc";
let b = "def"

i want to join them... on the net there are many ways but what do you use to do that?


1 Like

Fast String Concatenation? - #2 by DanielKeep ?

1 Like

Yes, but there is no other way other than to use to_string()? Is it impossibile working on &str? Just curious. thx.

1 Like

The methods used in the link by @dpc works fine directly on &str as well as on String. I would use the format! macro even though the linked performance measurement indicates it might not be optimal, because I think it signals the intent and makes the code simple.

let a = "abc";
let b = "def";
format!("{}{}", a, b)

If one of the strings are constant, I would embed that in the format string, e.g.:

let b = "def";
format!("abc{}", b)

If both are known compile-time, I would use the concat! macro:

concat!("abc", env!("SOMETHING"))

Added: As seen here, you don't have to convert the inputs from &str to String, but the return value of format! will be a String. The concat! macro will evaluate to a &'static str, but then all parts has to be known compile-time.

1 Like

Ah, very interesting. Thx a lot

You have to turn the &str into a String, because a &str is immutable.
So the only way is to make a new string with its contents.

K Steve, but if i want to create a new &str?

something like
let s1 = "a";
let s2 = "b"
let s3 = s1-joined-with-s2

You can always borrow a string, which auto-derefs to &str.

You can't create an &str. You can only create an owned, string of type String. Then you take a reference to it. Either a direct ref &String or a reference to the underlying slice &str.
The only &str that do not come from an owned String are the literals like "abcde" that you put in your code and have a static lifetime (they are &'static str), meaning they live as long as your program. (as well as const and static items I think.)

1 Like

let s1 = "a";
let s2 = "b";
let s3 = format!("{}{}", s1, s2);
let s3 = &s3[..];

That is, first make a String, then create a &str from it and use

1 Like

What's wrong with a simple:

let ref string = first.to_owned() + second;

There you have a new &str created from two &str without needing to spend time formatting.