Should I implement Display or ToString to render a

2019-01-28 00:29发布

问题:

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.

回答1:

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.



标签: string rust