我应该实现 Display 还是 ToString 以将类型呈现为字符串? [英] Should I implement Display or ToString to render a type as a string?

查看:33
本文介绍了我应该实现 Display 还是 ToString 以将类型呈现为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Foo 类型,我希望能够将它作为字符串显示给最终用户,通过实现 Display 或通过实现 ToString?

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?

如果 Display 是要走的路,我实际上如何以 String 结束?我怀疑我需要使用 write!,但我不完全确定如何使用.

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.

推荐答案

你不应该实现 ToString 手动.ToString trait 已经为所有实现了 fmt::Display:

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, 
{ /* ... */ }

如果您实现了 Displayto_string() 将自动在您的类型上可用.

If you implement Display, to_string() will be available on your type automatically.

fmt::Display 旨在为那些应该显示给用户的少数几种类型手动实现,而 fmt::Debug 预计将在 所有 类型中实现,以最好地表示它们的内部结构(对于大多数类型,这意味着他们应该有 #[derive(Debug)] .

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).

为了获得fmt::Debug输出的字符串表示,你需要使用format!("{:?}", value),和{:?} 是实现 fmt::Debug 的类型的占位符.

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定义何时使用 fmt::Debugfmt::Display 的指南.

RFC 565 defines guidelines for when to use fmt::Debug and fmt::Display.

这篇关于我应该实现 Display 还是 ToString 以将类型呈现为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆