jonadev95
jonadev95

Reputation: 367

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

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?

Upvotes: 9

Views: 3621

Answers (1)

DK.
DK.

Reputation: 59015

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:

Upvotes: 10

Related Questions