How to perform as much const evaluation as possible in println! macro

Currently I'm writting a small program with an optional feature, gpu

The program output a string like println!("process ({type}) finished with {code} after {time}",type = ..., code = ..., time = now.elapsed()), where the type is using GPU with gpu feature and isolated only without that feature.

I checked the output binaries, all the process (, ) finished with and the type are stored in different locations, which means a runtime concat will be performed.

That might be fine since I only call such println once, but I'm still curious about perform a const evaluation in this step. Is it possible to perform such const evaluation?

I know an ugly trait is that, store code and time manually, then write two different println! statements with or without feature gpu, but is it possible not to repeat the println! macro twice?

You can use #[cfg(...)] attributes to conditionally compile a macro that expands to either "using GPU" or "isolated only", then you can join the rest of your format string with the result of this macro using concat. It won't be particularly clean but it will get the job done without repeating the rest of the format string:

#[cfg(feature = "gpu")]
macro_rules! process_type { () => { "using GPU" } } 
#[cfg(not(feature = "gpu"))]
macro_rules! process_type { () => { "isolated only" } } 

fn main() {
    let code = 1;
    let time = "42 seconds";

    println!(concat!("process (", process_type!(), ") finished with {code} after {time}"), code = code, time = time);
}
1 Like

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.