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.
You should not implement
ToString
manually. TheToString
trait is already implemented for all types which implementfmt::Display
: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, whilefmt::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 useformat!("{:?}", value)
, with{:?}
being a placeholder for types which implementfmt::Debug
.RFC 565 defines guidelines for when to use
fmt::Debug
andfmt::Display
.