9

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Maxtron
  • 101
  • 4
  • 2
    Does this answer your question? [Does Rust have an equivalent to Python's unichr() function?](https://stackoverflow.com/questions/30531265/does-rust-have-an-equivalent-to-pythons-unichr-function) – user3840170 Mar 06 '22 at 09:19
  • @user3840170 Hmm... The OP also wants the opposite, which is as simple as `as u32`, but I don't see it mentioned on the linked question. – Chayim Friedman Mar 06 '22 at 09:38

2 Answers2

14

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);
}
Ekrem Dinçel
  • 1,053
  • 6
  • 17
2

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().

Błażej Czapp
  • 2,478
  • 2
  • 24
  • 18