想要在控制台打印输出彩色的字体,可以使用一些已经封装好的依赖库,比如ansi_term这个依赖库,官方依赖库地址:https://crates.io/crates/ansi_term
安装依赖:
cargo add ansi_term
或者在Cargo.toml文件中加入:
[dependencies]
ansi_term = "0.12"
使用ansi_term
,我们可以很容易地在Rust中使用彩色文本。下面是一个简单的示例代码:
use ansi_term::Colour::{Red, Green, Yellow, Blue, Purple, Cyan};
fn main() {
let err_msg = "这是错误消息";
println!("{} this is red", Red.paint(format!("ERROR MESSAGE: {}", err_msg)));
println!("{} this is green", Green.paint("SUCCESS:"));
println!("{} this is yellow", Yellow.paint("WARNING:"));
println!("{} this is blue", Blue.paint("INFO:"));
println!("{} this is purple", Purple.paint("DEBUG:"));
println!("{} this is cyan", Cyan.paint("TRACE:"));
}
输出效果: