Rust中的Python chr()和ord()是什么?

9
在Python中,你可以使用ord()chr()函数将整数转换为字符,将字符转换为整数。
>>>a = "a"
>>>b = ord(a) + 1
>>>b = chr(b)

我正在寻找一种在Rust中实现同样事情的方法,但是目前还没有发现类似的东西。


2
这回答了你的问题吗?Rust是否有类似于Python的unichr()函数的等效函数? - user3840170
@user3840170 嗯... OP 也想要相反的,就像 as u32 一样简单,但我没有在链接的问题中看到它被提到。 - Chayim Friedman
2个回答

14

你可以使用可用的IntoTryInto实现:

fn main() {
    let mut a: char = 'a';
    let mut b: u32 = a.into(); // char implements Into<u32>
    b += 1;
    a = b.try_into().unwrap(); // We have to use TryInto trait here because not every valid u32 is a valid unicode scalar value
    println!("{}", a);
}

1
这正是我正在寻找的。谢谢! - Maxtron

3

ord 可以使用 as 关键字 实现:

let c = 'c';
assert_eq!(99, c as u32);

在使用chr函数时,需要使用char::from_u32()函数:

let c = char::from_u32(0x2728);
assert_eq!(Some('✨'), c);

请注意,char::from_u32()在数字不是有效的码点时返回一个Option<char>。还有一个char::from_u32_unchecked()方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接