7

How does String::from("") & "".to_string() differ in Rust?

Is there any difference in stack and heap allocation in both cases?

Asnim P Ansari
  • 1,932
  • 1
  • 18
  • 41
  • 2
    Does this answer your question? [How to create a String directly?](https://stackoverflow.com/questions/31331356/how-to-create-a-string-directly) – joel Apr 28 '20 at 08:07

1 Answers1

12

How does String::from("") & "".to_string() differ in Rust?

They're part of different protocols (traits): std::convert::From and alloc::string::ToString[0].

However, when it comes to &str/String they do the same thing (as does "".to_owned()).

Is there any difference in stack and heap allocation in both cases?

As joelb's link indicates, before Rust 1.9 "".to_string() was markedly slower than the alternatives as it went through the entire string formatting machinery. That's no longer the case.


[0] `ToString` is also automatically implemented if the structure implements `Display`[1]

[1] functionally s.to_string() is equivalent to format!("{}", s), it's usually recommended to not implement ToString directly, unless bypassing the formatting machinery can provide significant performance improvements (which is why str/String do it)

Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • if they do the same thing and have the same performance why are different traits used? – Pioneer_11 Jun 21 '23 at 16:49
  • Because the traits have different purposes, they just happen to do the same thing for strings. `ToString` is auto-implemented for `Display`, it makes sense that Display-ing a string would be an identity, so you get a `String` with the same content as the original `str`. `From` converts A to B, it also makes sense that converting an `&str` to a `String` would be an identity allocation. Same with `ToOwned`, the owned version of an `&str` is the `String` with the same content. Maybe the core team could have left out `String::from(&str)` but... why? – Masklinn Jun 21 '23 at 17:29
  • so .to_string() is restricted to use only with &str's whereas String::from() can come from any type which has the right trait to allow a string to be generated from it? – Pioneer_11 Jun 21 '23 at 19:34
  • No, both work with any type for which they're implemented. `to_string` works with any type which implements `Display` (or `ToString` but that's rarely if ever implemented directly), and `String::from` works with any type for which `From for String` is implemented. – Masklinn Jun 21 '23 at 20:16
  • Ok in that case what is the difference in functionality between the two traits? – Pioneer_11 Jun 22 '23 at 01:46