Printing Tuples

Rust can do so many wonderful things, except to print a tuple.

I can print specific concrete tuples with known, possibly even generic, types. How many beginners will get stuck already on that? Now, suppose I want you to print a tuple of a uniform known type but simply of an unknown length. Not simple enough? By all means, I even allow you to restrict it to length <= 12.

For reference, the tuple rustdoc: tuple - Rust

I see that the longest Debug impl looks like it's for a 12-tuple.

1 Like

Yes but note that Display is not amongst the implementable traits.
I consider "Debug" mode to be "cheating", as I may actually want to print things out in release installations.

Well, you better not cheat or else the internet police will come and revoke your software engineering credentials.

1 Like

What would a Display print for a tuple look like?

If it's identical to the Debug implementation then just use that? It seems as though there was a miscommunication; you are allowed to use Debug prints in release mode.

3 Likes

The two things that come to mind are that debug formats are explicitly unstable, and that debug printing a tuple will debug print its contents.

1 Like

Yes but I wanted to do my own formatting.

It ended up being a lot of code, but here's what I came up with. It generally breaks down into 3 parts:

  • Traits to allow recursive code to process tuples, implemented by macro
  • An iterator implementation yielding dyn Display
  • A Display implementation for the iterator

Edit: On nightly, you can write the iterator to work generically with any trait object, instead of just Display

3 Likes

You have certainly risen to the challenge! I am impressed!

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.