如何在 Rust 中从另一个字符中减去一个字符? [英] How do I subtract one character from another in Rust?

查看:21
本文介绍了如何在 Rust 中从另一个字符中减去一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Java, I could do this.

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

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

I have tried the same in 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 中进行等价操作?

How can I do the equivalent operation in Rust?

推荐答案

该操作在 Unicode 世界中是没有意义的,在 ASCII 世界中几乎没有意义,这就是为什么 Rust 没有直接提供它,但是有两个根据您的用例执行此操作的方法:

The operation is meaningless in a Unicode world, and barely ever meaningful in an ASCII world, this is why Rust doesn't provide it directly, but there are two ways to do this depending on your use case:

  • 将字符转换为它们的标量值:'Z' as u32 - 'A' as u32
  • 使用字节字符文字:b'Z' - b'A'

这篇关于如何在 Rust 中从另一个字符中减去一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆