Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

I've written 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());
}

It should take the string and print it out on the console in red. When I try to to compile, the compiler says:

error: format argument must be a string literal.
 --> src/main.rs:4:16
  |
4 |     (write!(t, text)).unwrap();
  |                ^^^^

After a lot of searching, I've found out that I'm able to replace the text variable with e.g. "text" and it will work because it's a string literal, which the write! macro needs.

How could I use the write! macro with a string instead of a string literal? Or is there a better way to colourize the terminal output?

like image 879
jonadev95 Avatar asked Jul 26 '15 13:07

jonadev95


1 Answers

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


I think you're missing the thrust of the error message. write! has two mandatory arguments:

  1. A location to write to.
  2. A format string.

The second parameter is not just any arbitrary string, it's the format string.

See also:

  • println! error: expected a literal / format argument must be a string literal
like image 68
DK. Avatar answered Oct 28 '22 17:10

DK.