User-defined formatting parameters

Hi all,

I'd like to print out strings with ANSI terminal colors for colored output. I'd like to use a specific formatting like

println!("{:C}", x);

But it seems we can't define additional formatting parameters other than those already defined (as in std::fmt - Rust).

What is possible is to use the defined formatting traits (like Binary) and implement them for any user type we need.

Or maybe the best way is to implement a new macro to deal with that new formatting ?

Any idea welcome !

Define a newtype and implement Display for it.

1 Like

I would normally use a crate like owo-colours for this sort of thing.

use owo_colors::OwoColorize;

fn main() {
    // Foreground colors
    println!("My number is {:#x}!", 10.green());
    // Background colors
    println!("My number is not {}!", 4.on_red());
}
3 Likes

Is there a reason you prefer this over colored?

Not really.

I use color-eyre for doing pretty error handling and they already use owo-colors, so I'm using the same crate to keep the size of my dependency tree down.

1 Like

For the same reason, I usually use the color functionality in the console crate because I often use the console-dialoguer-indicatif triplet in my CLI apps.


Otherwise I end up making a tiny macro myself. But I really like H2CO3's suggestion above:

so I'll probably play with that more in the future.

Here's both macro and newtype examples
use std::fmt;

const AEC_BOLD_RED: &str = "\x1B[1;31m"; // bold red ANSI escape code
const AEC_RESET: &str = "\x1B[0m"; // reset ANSI escape code

/// Wraps a type that implements Display, and prints it in bold red
#[derive(Debug)]
struct BoldRed<T>(T);
impl<T: fmt::Display> fmt::Display for BoldRed<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}{}", AEC_BOLD_RED, self.0, AEC_RESET)
    }
}

/// Calls std::println!, all in bold red
macro_rules! br_println {
    ($($arg:tt)*) => ({
        ::std::println!("{}{}{}", AEC_BOLD_RED, ::std::format_args!($($arg)*), AEC_RESET);
    })
}

fn main() {
    println!("{}", BoldRed("I'm red."));
    br_println!("{}", "I'm red too!");
    println!("{}", "I'm not...");
}