Dynamic string formatting - macro format!

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

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=95bd374efff424b3d9152e7253881b64

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

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=660edeab3eab5a838ec524596143f27e

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

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

There are some more examples of that here:

https://doc.rust-lang.org/std/fmt/#width

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.