I'm trying to learn Rust and I got caught up thinking about how char
s are 4 bytes wide. I can cast a char
to a u32
and it works out (they are both 4 bytes wide), however, when I cast from a u32
to a char
, Rust complains:
fn main() {
let pizza_hex: u32 = 0x1f355;
let pizza: char = '
Every
char
is a validu32
value, but not everyu32
value is a validchar
.The property of
char
s holding valid Unicode codepoints factors into memory safety:To convert a
u32
to achar
at runtime, try this:If you just don't want creepy Unicode glyphs in your character literals, you can use Unicode escape sequences: