Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I subtract one character from another in Rust?

Tags:

char

rust

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?

like image 675
0x00A5 Avatar asked Feb 07 '19 22:02

0x00A5


1 Answers

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'
like image 169
mcarton Avatar answered Sep 21 '22 06:09

mcarton