Is there any way to avoid calling .to_string()
when I need a string? For example:
fn func1(aaa: String) -> ....
And instead of
func1("fdsfdsfd".to_string())
can I do something like this:
func1(s"fdsfdsfd")
Is there any way to avoid calling .to_string()
when I need a string? For example:
fn func1(aaa: String) -> ....
And instead of
func1("fdsfdsfd".to_string())
can I do something like this:
func1(s"fdsfdsfd")
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 useToString::to_string
. This works for any type that implementsDisplay
. This includes string slices, but also integers, IP addresses, paths, errors, and so on.Before Rust 1.9, the
str
implementation ofto_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 leveragesFrom::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 useto_owned
as it's much more obvious what is happening.No, the
str::to_string()
method is the canonical way of creating aString
from an&'static str
(a string literal). I even like it for the reason you dislike it: it's a little verbose. Because it involves a heap allocation, you should think twice before invoking it in cases such as these. Also note that since Rust gained impl specialization,str::to_string
is no slower thanstr::to_owned
or its ilk.However, what you really want here is a
func1
that can easily be passed any string, be it a&str
or aString
. Because aString
will Deref to a&str
, you can havefunc1
accept an&str
, thereby avoiding the String allocation altogether. See this example (playground):https://users.rust-lang.org/t/to-string-vs-to-owned-for-string-literals/1441/6?u=rofrol