Python's chr() and ord() in Rust
Asked Answered
V

2

10

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.

Vet answered 6/3, 2022 at 9:6 Comment(2)
Does this answer your question? Does Rust have an equivalent to Python's unichr() function?Emanative
@Emanative 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.Shivers
D
15

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);
}
Dirge answered 6/3, 2022 at 11:5 Comment(1)
it's exactly what I was lookin for. Thanks !Vet
D
4

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

Doer answered 3/12, 2022 at 17:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.