How do I subtract one character from another in Ru

2020-04-04 16:38发布

问题:

In Java, I could do this.

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

I have tried the same in Rust:

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

but the compiler complains:

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`

How can I do the equivalent operation in Rust?

回答1:

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:

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


标签: rust char