221. from_str_radix — Parse Hex, Binary, or Octal Without Hand-Rolling a Loop
Got a "ff" or a "1010" and need the number behind it? Don’t loop over the characters multiplying by 16. Every integer type has from_str_radix, which parses a string in any base from 2 to 36 in one call.
The hand-rolled version is easy to get subtly wrong — overflow, bad digits, off-by-one on the place value:
| |
from_str_radix does the whole thing, and returns a Result so bad input is an error instead of a panic or a wrong answer:
| |
It validates digits for you — a character outside the chosen base is a clean Err, not garbage:
| |
A real use: cracking a #RRGGBB color into channels. Slice, parse, done — no manual nibble math:
| |
Signed types work too, and a leading - is honored:
| |
For plain base-10 you don’t even need it — "42".parse::<u32>() is the same thing with the radix fixed at 10. Reach for from_str_radix the moment the base isn’t ten.