Print variables in color using crate colored 2.1.0

Hi, I'm currently using the crate colored v2.1.0, but I have a problem with printing variables. Here's an example:

use colored::*;

fn main() {
    let x = 1;
    println!("{}", "{x}".cyan());

It just prints "{x}" in cyan, and gives the following warning:

warning: unused variable: `x`
 --> src/
4 |     let x = 1;
  |         ^ help: if this is intentional, prefix it with an underscore: `_x`
  = note: `#[warn(unused_variables)]` on by default

warning: `test_colored` (bin "test_colored") generated 1 warning (run `cargo fix --bin "test_colored"` to apply 1 suggestion)
    Finished dev [unoptimized + debuginfo] target(s) in 0.44s
     Running `target/debug/test_colored`

Can someone explain why it doesn't work?

Looks like the Colorize trait (which provides the .cyan() method) is implemented only for strings. You need:

println!("{}", x.to_string().cyan());

Btw, the {x} syntax works only in the format string (println!'s first argument).

yansi is a similar crate, but its Paint trait is implemented for every type, so it won't need additional to_string().

1 Like

I rewrote my program using yansi, it works perfectly! Thanks a lot!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.