如何在 Rust 中将彩色文本打印到终端?

How do I print colored text to the terminal in Rust?

如何使用 Rust 将彩色文本输出到终端?我已经尝试使用我在 this python answer 中找到的特殊转义字符,但它们只是按字面意思打印。这是我的代码:

fn main() {
    println!("3[93mError3[0m");
}

欢迎任何见解!

您可以使用 colored crate 来执行此操作。这是一个简单的例子。具有多种颜色和格式:

use colored::Colorize;

fn main() {
    println!(
        "{}, {}, {}, {}, {}, {}, and some normal text.",
        format!("Bold").bold(),
        format!("Red").red(),
        format!("Yellow").yellow(),
        format!("Green Strikethrough").green().strikethrough(),
        format!("Blue Underline").blue().underline(),
        format!("Purple Italics").purple().italic()
    );
}

样本颜色输出:

每个格式函数(red()italics() 等)都可以单独使用,也可以与其他格式函数结合使用。但是,如果将 colors 组合使用,则只会显示最后设置的颜色。

Rust 没有八进制转义序列。您必须使用十六进制:

println!("\x1b[93mError\x1b[0m");

另见 https://github.com/rust-lang/rust/issues/30491

编辑: 发生了什么,编译器没有抱怨的原因是 [=11=] 有效的转义Rust 中的序列 - 代表 NULL 字符(ASCII 代码 0)。只是 Rust 与 C(和 Python)不同,不允许您在此之后指定八进制数。所以它认为 33 是要打印的普通字符。