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

Viewed 10156

How do I output colored text to the terminal using Rust? I've tried using the special escape characters that I found in this python answer, but they just print literally. Here is my code:

fn main() {
    println!("\033[93mError\033[0m");
}

Any insight is welcome!

2 Answers

You can use the colored crate to do this. Here is a simple example. with multiple colors and formats:

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

Sample color output:

colored and formatted text in the terminal with Rust

Each of the format functions (red(), italics(), etc.) can be used on it's own as well as in combination with others. But if you use colors in combination with each other, only the last color to be set shows.

Rust doesn't have octal escape sequences. You have to use hexadecimal:

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

See also https://github.com/rust-lang/rust/issues/30491.

Edit: What happens, and the reason the compiler does not complain, is that \0 is a valid escape sequence in Rust - and represents the NULL character (ASCII code 0). It is just that Rust, unlike C (and Python), does not allow you to specify octal number after that. So it considers the 33 to be normal characters to print.

Related