Is there a performance or stylistic reason to prefer one of the following forms for creating a String from a literal in Rust?
"hello world".to_string() format!("hello world") String::from("hello world") The idiomatic way in the Rust compiler internals and thus Rust in general is to use to_string. It is done this way in the compiler and backed by Alex Crichton in three pull requests (1, 2, 3) that tried to change this.
The argument is that to_string most clearly defines what you want. Performance-wise both to_string and format! are slower than String::from. But once we get impl specialization there's a good chance that they will perform exactly the same.
That said, clippy lints against "abc".to_string() and suggests "abc".to_owned().
String::from in most of the examples. I wonder if that should be changed if to_string is the preferred approach.String::from too, finding it conveniently explicit and performing well. Of course, it can be argued that it is better to focus on more general purpose methods, especially as specialization should take care of the performance aspect.String::from for literals, and to_string() for non-literals, so that's probably why newer docs have String::from().
format!, because the formatting machinery is heavy weight for such a straightforward translation.