Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I implement Display or ToString to render a type as a string?

Tags:

string

rust

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.

like image 746
Ray Avatar asked Jan 04 '15 19:01

Ray


1 Answers

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.

like image 167
Vladimir Matveev Avatar answered Sep 19 '22 14:09

Vladimir Matveev