gpt4 book ai didi

rust - 如何在 Rust 中从另一个字符中减去一个字符?

转载 作者:行者123 更新时间:2023-11-29 07:47:43 24 4
gpt4 key购买 nike

在 Java 中,我可以做到这一点。

int diff = 'Z' - 'A'; // 25

我在 Rust 中也尝试过同样的方法:

fn main() {
'Z' - 'A';
}

但是编译器提示:

error[E0369]: binary operation `-` cannot be applied to type `char`
--> src/main.rs:2:5
|
2 | 'Z' - 'A';
| ^^^^^^^^^
|
= note: an implementation of `std::ops::Sub` might be missing for `char`

我如何在 Rust 中进行等效操作?

最佳答案

该操作在 Unicode 世界中没有意义,在 ASCII 世界中几乎没有意义,这就是 Rust 不直接提供它的原因,但根据您的用例,有两种方法可以做到这一点:

  • 将字符转换为其标量值:'Z' as u32 - 'A' as u32
  • 使用字节字 rune 字:b'Z' - b'A'

关于rust - 如何在 Rust 中从另一个字符中减去一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54583399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com