Print symbols in color to the shell/terminal

I'm trying to print some capitalized letters with card symbols to the shell/terminal and came up with this:

let chars = vec![74, 226, 153, 163];
let clubs_jack: String = String::from_utf8(chars).unwrap();
let chars = vec![74, 226, 153, 165];
let hearts_jack: String = String::from_utf8(chars).unwrap();
// (see http://www.termsys.demon.co.uk/vtansi.htm#colors)
let esc_char = vec![27];
let esc = String::from_utf8(esc_char).unwrap();
let reset: u8 = 0;
let bright: u8 = 1;
let black: u8 = 30;
let red: u8 = 31;
println!("{}[{};{}m{}{}[{}m", esc, bright, black, clubs_jack, esc, reset);
println!("{}[{};{}m{}{}[{}m", esc, bright, red, hearts_jack, esc, reset);

Should look kind of like this:

J :clubs:
J :hearts:

Is there an easier or another solution?

There seems to be a few libraries for this sort of thing on crates.io, e.g. these seem promising:

Also, you can enter unicode symbols more directly than as UTF-8 encoded byte vectors. Either directly as the characters themselves, or with unicode escapes, e.g. '\u{1B}' is a char storing the escape character (one can also use "..." to get a &str), similarly \u{2663} is the clubs symbol.

1 Like

Also, you don't have to write the unicode code points yourself:

extern crate ansi_term;

use ansi_term::Colour::*;

fn main() {
    let clubs_jack = "J♣";
    let hearts_jack = "J♥";
    println!("{}", Black.bold().paint(clubs_jack));
    println!("{}", Red.bold().paint(hearts_jack));
}

Thanks a lot. To both of you. This obviously looks much cleaner.

Note that if you use ANSI escape codes, or a library which only uses ANSI escape codes, then Windows users won't be able to use your colors.

Thanks for the hint @retep998, I wasn't aware of that. It has been a while that work forced me to use Windows, but I guess those guys still using it could at least run code using ANSI escape codes with e.g. the Take Command Console (TCC). For now I just write some example code for myself to learn Rust (on OS X and Linux - even Linux terminals might run into UTF-8 problems). No intention to distribute anything to the Windows world :innocent: but good to know ...