Implications of call as_str() to create new String

Hi folks,

I am trying to figure out the best way to replicate a string.

I have two methods, listed below.

Method 1 creates a new String by calling the as_str() function. Using method 1, am I correct in thinking that a string slice with a static lifetime will be created? If so, is s2 now dependant on s1 which lives on the heap?

Method 2 creates a new String by calling the clone() function. Using method 2, am I correct in thinking that s1 can go out of scope and it will have no effect on s2?

// Method 1
let s1 = String::from("hello, world");
let s2 = String::from(s1.as_str());

// Method 2
let s1 = String::from("hello, world");
let s2 = s1.clone();

Any guidance would be greatly appreciated.

1 Like

No. calling .as_str() produces a &str that is valid for as long as s1 is usable. Then, calling String::from() on that will copy the text data to a new heap allocation, so the resulting String in s2 can be used independently from s1

1 Like

Yes, that's correct for method 2. Cloning s1 is actually what the compiler will advise you to do if you've moved its value before trying to use it again.

Thanks for the quick reply.

So the &str value is copied to a new String and allocated space on the heap, that makes sense.

From a resource point of view is method 1 is slightly better?

Thanks for getting back to me, that makes sense.

They are exactly the same.