8

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
jonadev95
  • 357
  • 1
  • 5
  • 15

1 Answers1

9

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
DK.
  • 55,277
  • 5
  • 189
  • 162