0

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

João Menighin
  • 3,083
  • 6
  • 38
  • 80
  • You are writing to stdout. This has absolutely nothing to do with a console! – William Pursell Apr 29 '22 at 20:00
  • This doesn't appear to be possible without rolling your own templating or using a crate, as `print!` and `format!` macros are parsed that at compile time, and thus cannot be something that isn't known at compile time. – Allan J. Apr 30 '22 at 01:11
  • Does this answer your question? [How can I use a dynamic format string with the format! macro?](https://stackoverflow.com/questions/32572486/how-can-i-use-a-dynamic-format-string-with-the-format-macro) – Chayim Friedman May 01 '22 at 11:31

1 Answers1

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);
}
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46