229. char::to_digit — Turn a Digit Character Into Its Value, Not Its Byte
Reached for c as u8 - b'0' to turn '7' into 7? It works until the input isn’t a digit — then you get silent garbage. char::to_digit does it safely and handles hex too.
The byte-math trap
The classic trick subtracts the ASCII code of '0':
| |
It’s fine for '0'..='9'. But there’s no validation — feed it anything else and the arithmetic just keeps going:
| |
No panic, no None — just a wrong number flowing downstream.
to_digit returns an Option
char::to_digit(radix) converts a digit character to its numeric value and gives you an Option<u32>, so non-digits become None instead of garbage:
| |
Pass 16 and it parses hex, letters included and case-insensitive:
| |
Where it shines
Because it returns an Option, it drops straight into filter_map — sum every digit in a string and skip everything else, no manual bounds check:
| |
The reverse direction
char::from_digit goes the other way — a value plus a radix back to a digit character:
| |
Both have been stable since Rust 1.0. Whenever you’re tempted to do char-to-number arithmetic by hand, reach for to_digit — it validates, it does hex, and it never silently lies to you.