0

I'm working through the MSLearn tutorial on Rust and in the topic on Strings I encounter this in an example that intentionally includes an error: "The compiler suggests that we can use the .to_string() function to make the conversion. In our examples, we use the String::from(&str) method."

So the tutorial writers must have had a reason for preferring String::from() over .to_string(). As a newcomer, should I assume that I should just stick with the one, hoping that someday I'll know enough to make my own choice? Or is this explainable?

RadlyEel
  • 309
  • 3
  • 11
  • 2
    Does this answer your question? [What is the difference between these 3 ways of declaring a string in Rust?](https://stackoverflow.com/questions/37149831/what-is-the-difference-between-these-3-ways-of-declaring-a-string-in-rust). Also [How does String::from("") & "".to_string() differ in Rust?](https://stackoverflow.com/q/61475158/11082165) – Brian61354270 Jul 17 '23 at 15:57
  • From the answer there, you would previously avoid `.to_string()` for this since it would incur a unnecessary performance hit, but that is no longer the case. So use whatever way you prefer. – kmdreko Jul 17 '23 at 16:05
  • They probably had a reason, but we can't read their mind. The Rust community is divided on what is better, though, each has its own advantages. Personally I prefer `.to_owned()`, but recently I started to think that maybe `.to_string()` is better, and `String::from()` is also an option I sometimes reconsider. – Chayim Friedman Jul 17 '23 at 16:55
  • Honestly, I have never understood why the trait `ToString` was even created in the first place. If you want to print some data to display them, then use either `Display` or `Debug`. If you need to convert the data into a string, use `Into`. If you want to serialize your data, use `serde`. I've never met an other usecase, and I feel like `ToString` is just a mixup – jthulhu Jul 17 '23 at 19:01
  • @jthulhu Integers, for example, don't implement `Into` (and rightfully so), and using `Display` is cumbersome (and slow). `ToString` is essentially a shorthand for single-element-to-string `Display` – Chayim Friedman Jul 18 '23 at 03:06

0 Answers0