Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rust have an equivalent to Python's unichr() function?

Tags:

rust

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?

like image 828
user1769868 Avatar asked May 29 '15 13:05

user1769868


1 Answers

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.

like image 105
Vladimir Matveev Avatar answered Sep 23 '22 05:09

Vladimir Matveev