Custom format specifier => trait pairs

In asking for help with an application, I wondered aloud in text whether (or perhaps assumed) it were possible to have:

trait DisplayType1 { ... }
trait DisplayType2 { ... }
// ...

and then somehow register that {:T1} and {:T2} should be handled by those traits.

cf. “The current mapping of types to traits

In my case, I wanted for a CLI to have a human-readable ‘pretty’ output (OK, Display works fine here) as well as JSON output (that should be different to Debug) and perhaps others in the future (e.g. one might imagine YAML, none, coloured, not).

It was suggested that I bring this up here, so here I am. (Note I’m not here to repeat my ‘what should I do’ question, just to identify a use case for something like this in the language.)

It should be possible to write your own macros that interpret just your custom format specifiers, and then pass on the rest to the standard format/print macros. That’d probably be the ideal way to test how useful/scalable this design is before any formal proposal.

1 Like

I think this is a perfect job for Newtypeman!

You can define a newtype around the value/type you want to display, then implement Display for it in the way you deem appropriate. A perfect example of this is the adapter module of the UUID crate.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.