Min*_*ful 4 unicode utf-8 rust
我刚刚学习 Rust,所以如果我错过了一种简单的方法来做到这一点,我深表歉意。我有一个程序,可以在运行时将 unicode 代码点作为字符串获取,并且我想将这些代码点转换为包含它们所代表的字符的 Rust 字符串。基本上,我试图弄清楚如何定义parse_unicode
以下代码。
fn parse_unicode(input: &str) -> String {
input.to_string() // not working implementation
}
#[test]
fn test_parse_unicode() {
let parsed_content = parse_unicode("1f44d");
assert_eq!(parsed_content, String::from("\u{1f44d}"));
}
Run Code Online (Sandbox Code Playgroud)
我看到有一个函数可以从字节数组转换为字符串,所以如果我自己编写代码来将这些代码点解析为字节数组,然后我可以将它们转换为字符串,但我希望有一个更惯用的(或者至少更简单的) ) 方法。
Stargateur 通过评论中链接的代码基本上解决了我的问题,如下所示:
use std::num::ParseIntError;
#[derive(Debug, PartialEq)]
enum Error {
Int(ParseIntError),
Unicode(u32),
}
fn parse_unicode(input: &str) -> Result<char, Error> {
let unicode = u32::from_str_radix(input, 16).map_err(Error::Int)?;
char::from_u32(unicode).ok_or_else(|| Error::Unicode(unicode))
}
#[test]
fn test_parse_unicode() {
assert_eq!(parse_unicode("1f44d"), Ok(''));
}
Run Code Online (Sandbox Code Playgroud)