You may want to check out the termcolor crate. It's designed to work on both Windows and *nix, which adding ANSI escape codes to your string wouldn't do.
From there it's just a case of iterating over the items and setting the foreground/background colour based on whatever that u8 means before printing the character.
Yeah but I need the color info to be directly encoded in the string, so it can later be reused (and some other technical reasons). Can termcolor do that as well ?
The Colored crate seems to do it.
I have no idea what it's doing but seems the formatted output actually goes into a 'String', and printing it retains the color
use colored::*;
fn main() {
let my_string: String = format!("{}", "hellow world".red());
println!("{}", my_string);
}
No, and that's by design. Because supporting the old Windows console APIs is incompatible with control codes embedded in the string.
If you don't care about supporting users who can only get color in their terminals via the Windows console APIs (older versions of Windows 10 IIRC along with anything older than Windows 10), then there are a number of crates in the ecosystem that only use ANSI escape sequences for color to choose from.