Rust format max-width

Hello

I have this basic string:

let string = format!("{: <4} {: <20} {: >6}\n", "1x", "Pizza Margherita (Small)", "25,90");

When outputting this on a small screen, this is the result:
Scherm­afbeelding 2023-09-19 om 02.28.59

I would like to keep the part 1x and 25,90 on the same height in the output. And the part `Pizza Margherita (Small) should be broken down in parts to fit in the small screen.

Wanted output:

1x   Pizza Margh        25,90
     erita (Small)

How would I achieve this?

That sort of layout isn't something format! (or any of the formatting code in the standard library) is capable of. Given that what you're describing is sensitive to the terminal width, you might want to search for "terminal tables" libraries on crates.io, or possible look into a Text User Interface library.[1]


  1. I can't give any recommendations because the last time I needed something in this vein, I got so frustrated with the options I could find that I ended up pitching a fit and writing my own. ↩︎

The problem is that I actually don't want to output it to the terminal, but want to have it in a string to send it to a thermal printer.

Hmm... in that case, I'd look for a table formatting crate that lets you directly specify the width constraint.

Any suggestions? I looked at prettytable.rs but that one also only outputs... no saving to string.

In that case, you want the support libraries and algorithms that go into building a Text User Interface. Try picking one with an appropriate license and scanning its parts.

This one is popular at least, and isn't just for outputting.
https://crates.io/crates/textwrap

I found it by first looking for hyphenation libraries and then their dependents.

(I haven't reviewed any of them.)

Where did you get that from? It can write to a generic writer, and Table directly implements Display.

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.