Does Rust have an equivalent python unichr () function?

Python has unichr() (or chr() in Python 3), which takes an integer and returns a character with the Unicode code point of that number. Does Rust have an equivalent function?

+8
rust
source share
1 answer

Of course, although this is a built-in as statement:

 let c: char = 97 as char; println!("{}", c); // prints "a" 

Note that the as operator only works for u8 numbers, something else will cause a compilation error:

 let c: char = 97u32 as char; // error: only `u8` can be cast as `char`, not `u32` 

If you need a string (to fully emulate the Python function), use to_string() :

 let s: String = (97 as char).to_string(); 

There is also a char::from_u32 :

 use std::char; let c: Option<char> = char::from_u32(97); 

It returns Option<char> , because not every number is a valid Unicode code point - the only valid numbers are: from 0x0000 to 0xD7FF and from 0xE000 to 0x10FFFF. This function is applicable to a larger set of values ​​than as char , and can convert numbers greater than one byte, providing access to the entire range of Unicode code points.

I put together a set of examples on the playground .

+13
source share

All Articles