Rust 是否有与 Python 的 unichr() 函数等效的函数? [英] Does Rust have an equivalent to Python's unichr() function?
问题描述
Python 具有 unichr()
(或 Python 3 中的 chr()
)函数,它接受一个整数并返回一个带有该数字的 Unicode 代码点的字符.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?
推荐答案
当然可以,虽然它是一个内置操作符as
:
Sure, though it is a built-in operator as
:
let c: char = 97 as char;
println!("{}", c); // prints "a"
请注意,as
运算符仅适用于 u8
数字,否则会导致编译错误:
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`
如果您需要一个字符串(以完全模拟 Python 函数),请使用 to_string()
:
If you need a string (to fully emulate the Python function), use to_string()
:
let s: String = (97 as char).to_string();
还有 char::from_u32代码>
函数:
use std::char;
let c: Option<char> = char::from_u32(97);
它返回一个 Option
因为不是每个数字都是有效的 Unicode 代码点 - 唯一有效的数字是 0x0000 到 0xD7FF 和从 0xE000 到 0x10FFFF.此函数适用于比 as char
更大的一组值,并且可以转换大于一个字节的数字,让您可以访问整个 Unicode 代码点范围.
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.
我在 Playground 上编译了 一组示例.
I've compiled a set of examples on the Playground.
这篇关于Rust 是否有与 Python 的 unichr() 函数等效的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!