'Use string variable as template for console output

new rustacean here!

I'm having a hard time using a string variable with placeholders as a template for println! and write!. Is it possible?

Example:

Let's say I have numbers I want to print in the following format: ~~## 10 ~~##

What I have working:

pub fn print_numbers(n1: u8, n2: u8, n3: u8) {
    println!("~~## {} ~~##", n1);
    println!("~~## {} ~~##", n2);
    println!("~~## {} ~~##", n3);
}

What I would like to do like:

pub fn print_numbers(n1: u8, n2: u8, n3: u8) {
    let template = "~~## {} ~~##";
    println!(template, n1);
    println!(template, n2);
    println!(template, n3);
}

The compilar only suggests me I should use a string literal like "{}". How can I create reusable string templates like this?

Thanks



Solution 1:[1]

I don't think it's possible at the moment since format argument required to be a string literal. One workaround solution would to define a closure and call it whenever needed.

pub fn print_numbers(n1: u8, n2: u8, n3: u8) {
    let render_custom_template = |num| println!("~~## {} ~~##", num);
    render_custom_template(n1);
    render_custom_template(n2);
    render_custom_template(n3);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abdul Niyas P M