Implementing ToString instead of Display

The documentation is fairly emphatic that "ToString shouldn’t be implemented directly: Display should be implemented instead, and you get the ToString implementation for free".

Is that still valid for cases where you just don't need Display and only ToString is required?

For private internal types, you can do whatever you want. But for a public API, Display is more flexible, as it works with the formatting macros (println, format, and so on), and it's available in #![no_std] environments where ToString isn't available. Also, implementing Display is not complicated, so there is little reason not to do it.

One counterpoint is that in some cases, it's possible for a manual ToString implementation to optimize better, compared to the blanket impl for Display. This should rarely matter, though.

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.