Does Rust have an equivalent to Python's unich

2019-02-21 18:17发布

问题:

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

回答1:

Sure, though it is a built-in operator as:

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

Note that as operator works only 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 the char::from_u32 function:

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

It returns an Option<char> because not every number is a valid Unicode code point - the only valid numbers are 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 larger than one byte, providing you access to the whole range of Unicode code points.

I've compiled a set of examples on the Playground.



标签: rust