rustchrord

Python's chr() and ord() in Rust


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.


Solution

  • You can use the available Into and TryInto implementations:

    fn main() {
        let mut a: char = 'a';
        let mut b: u32 = a.into(); // char implements Into<u32>
        b += 1;
        a = b.try_into().unwrap(); // We have to use TryInto trait here because not every valid u32 is a valid unicode scalar value
        println!("{}", a);
    }