为什么 #[derive(Show)] 不再起作用? [英] Why does #[derive(Show)] not work anymore?

查看:67
本文介绍了为什么 #[derive(Show)] 不再起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在今天的 Rust nightly 中,以下代码不再编译:

With today's Rust nightly the following code doesn't compile anymore:

#[derive(Show)]
enum S {
    A,
    B
}

fn main() {
    println!("{}", S::A);
}

相反,它给了我以下错误消息:

Instead it gives me the following error message:

error: the trait `core::fmt::String` is not implemented for the type `S`

有没有办法获得旧的行为?当然不能要求每个类型都手动实现.

Is there a way to get the old behaviour? Surely it can't be required to implement this by hand for each type.

推荐答案

旧的 Show trait 被拆分为 DisplayDebug.

The old Show trait was split into Display and Debug.

  • Display 专为面向用户的输出而设计,并使用空白/默认格式说明符(例如 {}{:.10} {foo:} 都是使用Display)

  • Display is designed for user-facing output, and uses the blank/default format specifier (e.g. {}, {:.10} {foo:} are all using Display)

Debug 设计用于调试/内部输出并使用 ? 格式说明符(例如 {:?}, >{:.10?}, {foo:?} 都是使用Debug)

Debug is designed for debugging/internal output and uses the ? format specifier (e.g. {:?}, {:.10?}, {foo:?} are all using Debug)

因此,要使用由 #[derive(Debug)] 创建的实现,应该编写 println!("{:?}", ...),而不是旧的 println!("{}", ...).

Hence, to use the implementation created by #[derive(Debug)] one should write println!("{:?}", ...), instead of the old println!("{}", ...).

只有 Debug 可以被 #[derive]d 因为像 Foo { x: 1, y: 2 } 这样的输出不太可能是正确的面向用户的输出,对于大多数情况(我确定它适用于某些情况,但是程序员可以编写 Display 的实现来自己完成,甚至直接调用 >#[derive]d Debug 实现).

Only Debug can be #[derive]d since output like Foo { x: 1, y: 2 } is unlikely to be the correct user-facing output, for most situations (I'm sure it is for some, but then the programmer can write the implementation of Display to do that themselves, or even call directly into the #[derive]d Debug implementation).

这最初在 RFC 504 并且在 中正在进行讨论RFC 565,使上述指南更加具体.

This was originally described in RFC 504 and there is ongoing discussion in RFC 565, making the guidelines stated above more concrete.

这篇关于为什么 #[derive(Show)] 不再起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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