28

I have a type Foo that I want to be able to display to the end user as a string, is it more idiomatic to do this by implementing Display or by implementing ToString?

If Display is the way to go, how would I actually end up with a String? I suspect I need to make use of write!, but I'm not entirely sure how.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ray
  • 1,769
  • 1
  • 17
  • 22

1 Answers1

39

You should not implement ToString manually. The ToString trait is already implemented for all types which implement fmt::Display:

impl<T> ToString for T
where
    T: Display + ?Sized, 
{ /* ... */ }

If you implement Display, to_string() will be available on your type automatically.

fmt::Display is intended to be implemented manually for those select few types which should be displayed to the user, while fmt::Debug is expected to be implemented for all types in such a way that represents their internals most nicely (for most types this means that they should have #[derive(Debug)] on them).

In order to obtain the string representation of fmt::Debug output you need to use format!("{:?}", value), with {:?} being a placeholder for types which implement fmt::Debug.

RFC 565 defines guidelines for when to use fmt::Debug and fmt::Display.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Vladimir Matveev
  • 120,085
  • 34
  • 287
  • 296