3

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") 
4
  • At the very least, avoid format!, because the formatting machinery is heavy weight for such a straightforward translation. Commented Nov 13, 2015 at 10:30
  • Reminder to all would be answerers: StackOverflow is not a forum and thus is not about debating; answers should strive for objectivity and be backing by authoritative references (such as the official style guide or a core developer's opinion). Commented Nov 13, 2015 at 10:32
  • 1
    @MatthieuM. to_string() also uses the formatting machinery. Commented Nov 13, 2015 at 10:38
  • @fjh: Ah yes, in the absence of specialization it's probably unavoidable. Commented Nov 13, 2015 at 10:49

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

6 Comments

Exact link to clippy's warning (with rationale): github.com/Manishearth/rust-clippy/wiki#str_to_string
Interesting. The String documentation uses String::from in most of the examples. I wonder if that should be changed if to_string is the preferred approach.
@JimmyCuadra I don't think it should. to_string is one core developer's preferred method, not the preferred approach. There are performance arguments against it (see e.g. this), and I don't really by the argument that to_string is clearer than String::from.
@JimmyCuadra: I actually do not find it strange; in documentation you want to focus on the API at hand and therefore using extraneous functions/types may be distracting (users will wonder where they come from). That being said, if you follow the link (1) from ker you will see that others seem to have switched to using 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.
I prefer String::from for literals, and to_string() for non-literals, so that's probably why newer docs have String::from().
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.