Embedding style / color in a newtype for Display trait

I'm trying to understand whether and why this is a bad practice because I see controversial opinions on this.

I have a value in my program that it is stored as f64 in a TOML file using serde but I want to print it in the form +x.yz% (in green) when it is positive and -x.yz% (in red) when negative (using the owo-colors crate for ANSI colors).

Since the value is mostly printed in a table using the tabled crate, I was thinking to create a newtype encapsulating the f64 value and implementing at least the Display and Into<String> trait on the newtype that is giving me the value already formatted and color-escaped.

Is this a good practice?

The other solution is creating a new Trait myself with a new function (for example .display_with_colors()) instead of overwriting the Display trait but I cannot see a real advantage in this (but I'm probably missing some nuances).

I think the newtype pattern with your own Display implementation is fine. You also have the option to only wrap the type[1] when displaying.

You may consider making colored-or-not a dynamic decision (based on flags/configuration/is_terminal).


  1. or a reference to the type, when not Copy ↩︎

1 Like