How to create a String directly?

TL;DR:

As of Rust 1.9, str::to_string, str::to_owned, String::from, str::into all have the same performance characteristics. Use whichever you prefer.


The most obvious and idiomatic way to convert a string slice (&str) to an owned string (String) is to use ToString::to_string. This works for any type that implements Display. This includes string slices, but also integers, IP addresses, paths, errors, and so on.

Before Rust 1.9, the str implementation of to_string leveraged the formatting infrastructure. While it worked, it was overkill and not the most performant path.

A lighter solution was to use ToOwned::to_owned, which is implemented for types that have a “borrowed” and an “owned” pair. It is implemented in an efficient manner.

Another lightweight solution is to use Into::into which leverages From::from. This is also implemented efficiently.


For your specific case, the best thing to do is to accept a &str, as thirtythreeforty answered. Then you need to do zero allocations, which is the best outcome.

In general, I will probably use into if I need to make an allocated string — it’s only 4 letters long ^_^. When answering questions on Stack Overflow, I’ll use to_owned as it’s much more obvious what is happening.

Leave a Comment