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


#1

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

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


#3

https://doc.rust-lang.org/std/fmt/struct.Formatter.html#method.alternate


#4

If your custom Debug format has a “standard” shape, you can use the debug builders, which will handle alternate formatting automatically for you: https://doc.rust-lang.org/std/fmt/struct.Formatter.html#method.debug_struct


#5

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.


#6

# 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?


#7

“pretty-print” ?


#8

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


#9

# - 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 ?)


#10

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


#11

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


#12

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