For all the primitive integer types in Rust, the from_str_radix method, which converts a string in the given radix to an integer, takes a u32 integer as the argument for the radix. Given that the function panics if the radix is not in the range [2, 36], why doesn't from_str_radix take a u8 instead of a u32, as a u8 can already store larger integers than the largest allowed radix?
This sort of thing also occurs in other integer methods such as pow. The largest value of a u8 is 255 and 2^255 is already larger than the maximum value that can be stored by a u128 (the largest integer type in Rust), so why does the pow function take a u32, seeing as most u32 values for the exponent will cause an overflow?
Per Niko in #22240 (emphasis added):
These are the guidelines that we intend to follow in the standard library. These guidelines are not intended as universal guidelines to be used outside the standard library (though of course one might choose to do so).
- Use unsigned values if the value should always be greater than or equal to zero, and signed values otherwise.
- For indices, pointers, or other values which are tied to a data structure whose size is proportional to the size of memory, use
usizeorisize.- For cases where the acceptable domain of a value perfectly fits a fixed number of bits, use the appropriate fixed-size type. For example, a method like
write_u16would take au16argument.- Otherwise, use
i32/u32if the value has a narrow range andi64/u64otherwise.Examples:
- Vector indices and hashmap lengths use
usize.- The size of a file would be
u64, as the maximum size of a file is not tied to addressable memory.- Something like
write_u16takes au16(shocker, I know!)- The radix of an integer would use
u32.
- You might expect
u8, since a radix higher than 256 is not useful, but the domain of useful radices is actually much smaller thanu8, so usingu8isn't providing a meaningful guarantee, and will simply increase friction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With