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

I have a type Foo

that I want to show to the end user as a string, is it more idiomatic to do this by implementation Display

or by implementation ToString

?

If Display

- is this the way, how would I actually end up with String

? I suspect I need to use it write!

, but I'm not really sure how.

+3


source to share


1 answer


Cannot be done ToString

manually. The sign is ToString

already implemented for all types that implement fmt::Display

. If you implement Display

, to_string()

will be available on your type automatically.

fmt::Display

intended for manual input for those who select multiple types that should be displayed to the user, and fmt::Debug

is expected to be implemented for all types in a way that most beautifully represents their insides (for most types this means they must have #[derive(Debug)]

on them) ...



To get a string representation of the output fmt::Debug

, you need to use format!("{:?}", value)

, and {:?}

is a placeholder for the types that implement fmt::Debug

.

RFC 565 defines guidelines for the use of fmt::Debug

and fmt::Display

.

+5


source







All Articles