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