How to create multiple formatted string without repeating the format string?

Hi! I'm new to Rust. Not sure if such a basic question belongs to this forum.

I'm trying to create formatted strings in many places in a program, in some other languages I can store the format string in a constant and use it in the formatting function:

const FORMAT = "%-30v | %2v | %2v | %2v | %2v | %2v\n"
s1 = sprintf(FORMAT, ...)
s2 = sprintf(FORMAT, ...)

This way, if the format string need change later, I can conveniently change it in one central place, without having to search and replace every single instance littered around the program.

However in Rust I'm not able to do this due to format! only accepting literal as format string.

Is it possible to work around this issue, preferably avoid pulling other crates?

Thanks!

1 Like
macro_rules! my_format {
    ($($args:tt)*) => {format!("format string", $($args)*)}
}

https://doc.rust-lang.org/rust-by-example/macros.html

1 Like

Thanks! I've yet to learn the macro system but it looks like the right solution.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.