如何使用Rust将彩色文本输出到终端?我尝试使用在this python answer中找到的特殊转义字符,但它们只是字面打印出来。这是我的代码:
fn main() {
println!("\033[93mError\033[0m");
}
fn main() {
println!("\033[93mError\033[0m");
}
colored
crate来实现这个功能。下面是一个简单的例子,包含多种颜色和格式:use colored::Colorize;
fn main() {
println!(
"{}, {}, {}, {}, {}, {}, and some normal text.",
"Bold".bold(),
"Red".red(),
"Yellow".yellow(),
"Green Strikethrough".green().strikethrough(),
"Blue Underline".blue().underline(),
"Purple Italics".purple().italic()
);
}
red()
,italics()
等)都可以单独使用,也可以与其他函数组合使用。但是,如果你将颜色与其他颜色组合使用,只有最后设置的颜色会显示出来。format!
宏 - 你可以直接在实际的&str
上调用Colorize
函数(例如,"Bold".bold()
可以代替format!("Bold").bold()
)。 - iamkneelRust没有八进制的转义序列。你需要使用十六进制:
println!("\x1b[93mError\x1b[0m");
请参阅https://github.com/rust-lang/rust/issues/30491。
发生的事情是,编译器不会报错的原因是在 Rust 中\0
是有效的转义序列,并表示 NULL 字符(ASCII 码为0)。与 C(和 Python)不同的是,Rust 不允许在此之后指定八进制数字。所以它将 33
视为要打印的普通字符。
cargo add inline_colorization
use inline_colorization::*;
fn main() {
println!("Lets the user {color_red}colorize{color_reset} the and {style_underline}style the output{style_reset} text using inline variables");
}