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

查看:150
本文介绍了如何在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`


$ b可能缺少std :: ops :: Sub`的实现$ b

如何在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'作为u32-'A'作为u32

  • 使用字节字符文字: b'Z'-b'A'

  • Cast the characters to their scalar value: 'Z' as u32 - 'A' as u32
  • Use byte character literals: b'Z' - b'A'

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

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