首页 > 解决方案 > 为什么用彩色箱子中的彩色字符串替换子字符串不起作用?

问题描述

我正在尝试用彩色版本替换给定字符串的所有出现:

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() {}

第一个println!按预期工作并以红色打印文本,但第二个println!按预期工作并以默认颜色打印文本。

字符串文字似乎丢失了颜色信息。我想找到一个replace可以打印我想要的文本的等价物。

标签: stringrust

解决方案


ColoredStringimplements Deref<Target = str>,但返回的&str不包含任何颜色信息。您可以通过打印出取消引用的字符串来看到这一点:

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

看来正确的做法是将彩色文本转换为 aString并将其用于格式化。

此外:

  • 拿一个&String是没用的。
  • 在替换之前克隆String它是没用的
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);
}

也可以看看:


推荐阅读