In Python you can convert an integer into a character and a character into an integer with ord()
and chr()
:
>>>a = "a"
>>>b = ord(a) + 1
>>>b = chr(b)
I am looking for a way to do the same thing in Rust, but I have found nothing similar yet.
ord
can be done using the as
keyword:
let c = 'c';
assert_eq!(99, c as u32);
While chr
using the char::from_u32()
function:
let c = char::from_u32(0x2728);
assert_eq!(Some('✨'), c);
Note that char::from_u32()
returns an Option<char>
in case the number isn't a valid codepoint. There's also char::from_u32_unchecked()
.
You can use the available
Into
andTryInto
implementations: