Joining str: many ways


#1

Simple:

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?

thx.


#2

Fast String Concatenation? ?


#3

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


#4

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.


#5

Ah, very interesting. Thx a lot


#6

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.


#7

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


#8

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


#9

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.)


#10

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
shadowing.


#11

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.