Use write! macro with a string instead of a string literal

I wrote the following function:

fn print_error(text: &str){
    let mut t = term::stdout().unwrap();
    t.fg(term::color::RED).unwrap();
    (write!(t, text)).unwrap();
    assert!(t.reset().unwrap());
}

As you can see, he should take the line and print it on the console in red. But when I try to compile, the compiler says:

error: format argument must be a string literal.

After many searches, I found that I could replace a text variable, for example. "text", and it will work because it is a string literal that a macro requires write!.

But how can I use a macro write!with a string instead of a string literal? Or is there a better way to color output terminal output?

+4
source share
1 answer

I think you are missing the push of the error message. The second parameter is not an arbitrary string; it is a format string.

write!(t, "{}", text).

+4

Source: https://habr.com/ru/post/1599729/


All Articles