What is the idiomatic way to convert &str to String?

Let's go over what each of these means semantically:

  • to_owned: I have a borrowed object and I want an owned version
  • to_string: I want the textual representation of something
  • into (or String::from): I want a generic type conversion
  • format!: I want a textual representation of something in a particular representation. Basically a fancy way of calling to_string (to_string is implemented generically for Display, the canonical way of using Display is through format!)

I think in most cases what you mean to do is to_owned. into is fine but conveys less intent. In cases where the type can be inferred, for example as a function argument, I think into is fine.

Don't use format! if you can use to_string, less overhead.

22 Likes