Why does #[derive(Show)] not work anymore?

北城余情 提交于 2019-12-03 23:39:24

问题


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.


回答1:


The old Show trait was split into Display and Debug.

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

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

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

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

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




回答2:


The answer is to use {:?} instead of {} in format!.



来源:https://stackoverflow.com/questions/27874987/why-does-deriveshow-not-work-anymore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!