Dynamic string formatting - macro format!

Hello,
I would like to dynamically change/modify the formatting argument for e.g. "{:02X}"
How to do it?

You can't. If you want to support dynamic formatting, you have to model the format switch yourself, like this:

If you only want to change the width, then the following will work:

fn main() {
    let value: u32 = 1234;
    println!("{:0width$}", value, width = 10)
}
2 Likes

There are some more examples of that here:

I would like to dynamically set the format string - "{}", set the number format - hex, dec etc.

You could do this:

use std::{fmt, fmt::Display, fmt::UpperHex};

enum NumberFmt<T> {Dec(T), Hex(T)}

impl<T: Display+UpperHex> Display for NumberFmt<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            NumberFmt::Dec(x) => write!(f, "{}", x),
            NumberFmt::Hex(x) => write!(f, "{:02X}", x)
        }
    }
}

fn main() {
    let dec = NumberFmt::Dec; // These are function pointers, which
    let hex = NumberFmt::Hex; // can be stored in data structures.
    println!("{}", dec(255));
    println!("{}", hex(255));
}

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.