Custom `fmt::Debug` implementation: Handle `{:#?}` pretty printing

I have a custom implementation of fmt::Debug for one of my types. Right now it doesn't handle the {:#?} pretty printing formatter.

Is it possible to detect inside fmt::Debug::fmt that it's called for a pretty-printed version of self?

2 Likes

Check out the alternate() method on the Formatter that is handed to you inside Debug::fmt().

3 Likes
2 Likes

If your custom Debug format has a "standard" shape, you can use the debug builders, which will handle alternate formatting automatically for you: Formatter in std::fmt - Rust

5 Likes

Thanks! I wasn't aware of the alternate flag (and find the name a bit misleading to be honest). I should have read the documentation a bit more thorough :slight_smile:

Also good to know that debug_struct handles the flag too.

# is the alternate printing form flag, and is also used for e.g. having the printer prepend 0x to a hex number. What would you think would be a better name for the alternate method?

"pretty-print" ?

1 Like

That would be a good idea, but for better or worse, the alternate flag is overloaded to be more than just pretty-print (it's in the page @kyrias linked).

# - This flag is indicates that the "alternate" form of printing should be used. The alternate forms are:

  • #? - pretty-print the Debug formatting
  • #x - precedes the argument with a 0x
  • #X - precedes the argument with a 0x
  • #b - precedes the argument with a 0b
  • #o - precedes the argument with a 0o

All these look like they could be assimilated to pretty-print to me. Also maybe alternate is semantically more correct but it lost some meaning en route.
(Lastly could you spot the grammar inconsistency in that quoted snippet ?)

Didn’t mean to start a discussion here :slight_smile: I just wish there was a bit more documentation around the subject. Maybe it’s worth adding a paragraph about this topic to the book or a section in fmt::Formatter's documentation

I think @steveklabnik would be happy to accept such a PR :wink:

Sure thing, but to the API docs, not the book :slight_smile:

1 Like