Console
colorIn Rust, console colors can be used with external crates that have convenient syntax. But this is not always desirable.
With a short
function, we can implement our own console coloring logic. This reduces an external dependency in the project, and can lead to further improvements.
With ANSI codes, we can use numbers to indicate colors and whether text is bold. Other display features can be set, but colors and bolding are the most useful.
get_color
is called, it adds the prefix syntax for ANSI display information.fn get_color_code(name: &str) -> &'static str { // Limited ANSI color converter. if name == "red" { "1" } else if name == "green" { "2" } else if name == "blue" { "4" } else if name == "white" { "7" } else { "0" // Black. } } fn get_color(value: &str, bold: bool, color: &str, background: &str) -> String { // Get string with console color information. let mut result = String::from("\u{1b}["); // [1;] means bold. if bold { result.push_str("1;"); } // Handle foreground. if !color.is_empty() { result.push_str("38;5;"); // Codes for ANSI foreground. result.push_str(get_color_code(color)); result.push(';'); } // Handle background. if !background.is_empty() { result.push_str("48;5;"); // Codes for ANSI background. result.push_str(get_color_code(background)); result.push(';'); } result.push_str("7m"); // End token. result.push_str(value); result.push_str("\u{1b}[0m"); result } fn main() { println!("{}", get_color("TEST", true, "blue", "")); println!("{}", get_color("TEST", true, "green", "")); println!("{}", get_color("OK", false, "black", "")); println!("{}", get_color("OK", false, "", "")); println!("{}", get_color("TEST", true, "blue", "white")); println!("{}", get_color("TEST", true, "green", "")); println!("{}", get_color("OK", false, "black", "")); println!("{}", get_color("OK", false, "", "")); println!("{}", get_color("RED", true, "red", "")); println!("{}", get_color("abc", true, "green", "black")); }TEST TEST OK OK TEST TEST OK OK RED abc
With these functions, we can often reduce a crate dependency and handle colors directly. And with the simple logic, we can make programs follow more unified themes.
get_color_code
function.Handling colors directly in Rust programs with a custom function can sometimes be desirable. The ANSI codes are understandable once we learn the syntax.