Idiomatic to implement the `Debug` trait for `x?` syntax

I was going implement Debug for a type to support the :x? syntax in formatting (it's for debug printing in hexadecimal). I'm not sure if it's widely used, but indeed it's mentioned in the std doc and I do have potential usages for it.

The question is, the docs says :x? should also be supported through the trait Debug, but the Formatter type doesn't have a method to tell whether Debug is called by :? or :x?. After some investigation into the compiler, I found that this information is captured in the Formatter's flags. So I had a try:

use std::fmt;

struct Dummy;

impl fmt::Debug for Dummy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        f.write_fmt(format_args!("called Debug with flags {}", f.flags()))
    }
}

fn main() {
    println!("{:?}", Dummy);
    println!("{:#?}", Dummy);
    println!("{:x?}", Dummy);
    println!("{:X?}", Dummy);
}

The output is

called Debug with flags 0
called Debug with flags 4
called Debug with flags 16
called Debug with flags 32

So, the flags indeed tell us how the trait is called. However, the flags method is deprecated, so it should not be used in new code. Then what is the idiomatic way to support the x? syntax? Or is this syntax actually also going to be deprecated?

1 Like

With the LowerHex and UpperHex traits. (see here for the list of fmt traits)

That's for {:x}, not for {:x?}, though. (It doesn't seem like there is a public and documented way for getting the "is hex?" flag in Debug impls.)

1 Like

Some discussion in the tracking issue of the original "debug hex" feature. Seems there wasn't a consensus between just providing a simple getter or whether there should be a more generic and future-proof API for getting the various formatting flags.

Edit: PR to add extensible API

Unless I'm misreading (entirely possible) OP is asking for :x? not x:? (which would just be the Debug print for the variable x).

EDIT: AH I see my mistake !

I misspelled the format specifier in my earlier post (fixed now), but OP's code wouldn't compile with LowerHex, as :x? still calls Debug, not LowerHex.

1 Like

Thanks for pointing me to that tracking issue! At the bottom there seems to be a PR related to this. So I guess right now the way to implement this is still relying on the flags method until someday a new API is proposed?

1 Like

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.