1

I'm trying to replace all the occurrences of a given string with a colorized version:

extern crate colored; // 1.6.1

use colored::Colorize;

fn print_found_line(x: &i32, line: &String, found: &str) {
    let mut line_to_print: String = line.clone();

    println!("{}", found.red()); // work
    line_to_print = line_to_print.replace(found, found.red().as_ref());
    println!("[{}] {}", x.to_string().blue(), line_to_print); // the found string replaced is not red
}

fn main() {}

The first println! works as intended and prints the text in red, but the second println! does not work as intended and prints the text in the default color.

It seems that the string literal loses the color information. I want to find a replace equivalent that prints the text as I want.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Arthur Saint-Genis
  • 167
  • 1
  • 2
  • 12

1 Answers1

3

ColoredString implements Deref<Target = str>, but the returned &str doesn't include any color information. You can see this by printing out the dereferenced string:

println!("{}", found.red().as_ref() as &str);

It appears that the correct thing to do is to convert the colored text into a String and use that for formatting.

Additionally:

  • Taking a &String is useless.
  • Cloning the String before replacing it is useless
fn print_found_line(x: &i32, line: &str, found: &str) {
    let line_to_print = line.replace(found, &found.red().to_string());
    println!("[{}] {}", x.to_string().blue(), line_to_print);
}

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Thanks a lot, I tried with a simple to_string() before but it wasn't compiling as the 'to' parameter was not a &str. I must have miss something obvious at that moment. I accepted your answer and everything is working as intended. – Arthur Saint-Genis Oct 13 '18 at 13:19