Rust Reference ยท Core Traits
The ToString trait
Reference for Rust ToString: the blanket implementation for every Display type, to_string() cost, specialization for str and numbers, and when not to implement it.
ToString is the trait behind the .to_string() method. It has a single method that turns a value into an owned String. You almost never implement it yourself: the standard library provides a blanket implementation for every type that implements Display, so implementing Display gives you to_string() for free.
Because of that blanket implementation, to_string() works on integers, floats, char, bool, &str, String, and any of your own types that implement Display.
let s: String = 42.to_string();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait ToString { fn to_string(&self) -> String; } impl<T: fmt::Display + ?Sized> ToString for T { /* provided by std */ }
| Name | Description |
|---|---|
&self |
The value to format. It is only borrowed. |
Returns: a new String containing exactly what format!("{}", value) would produce.
Errors / panics / edge cases: to_string() panics if the Display implementation returns an error, because a String cannot fail to accept text. A correct Display implementation only returns errors that come from the writer, so this does not happen in practice.
Usage notes
- Implement
Display, notToString. A manualimpl ToString for MyTypeconflicts with the blanket implementation and does not compile. The one exception is a type that does not implementDisplay, which is rare and usually a design smell. - It allocates. Every call creates a new
String. To print or to write into an existing buffer, useprintln!,write!or thefmt::Writetrait instead. - Fast paths exist. The standard library specializes
to_string()forstr,String,char,booland the integer types, so these skip the general formatting machinery. Behavior is identical. - Not the same as
Debug.to_string()usesDisplay. A type that only implementsDebughas noto_string(); useformat!("{:?}", v). - Accepts unsized types. The
?Sizedbound meansstritself is covered, so"text".to_string()works through auto-referencing. to_string()versusto_owned()andString::from. For a&strall three give the sameString. Pick one style per codebase;.to_string()is the most common in examples.- Formatting options are lost. Width, precision and fill are formatter flags, so
to_string()always uses the default ones. Useformat!("{:>8.2}", x)when you need them. - Generic code. Write
T: ToStringwhen you only need text out, andT: Displaywhen you also want to print it directly. Both accept the same types.
Related
Display,fmt::Write,FromStr,FromandInto- Lessons: Display and From, Printing, Strings