Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of the u32 integer type in rust

Tags:

rust

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?

like image 320
isaacholt100 Avatar asked Jan 25 '23 08:01

isaacholt100


1 Answers

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).

  1. Use unsigned values if the value should always be greater than or equal to zero, and signed values otherwise.
  2. For indices, pointers, or other values which are tied to a data structure whose size is proportional to the size of memory, use usize or isize.
  3. 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_u16 would take a u16 argument.
  4. Otherwise, use i32/u32 if the value has a narrow range and i64/u64 otherwise.

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_u16 takes a u16 (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 than u8, so using u8 isn't providing a meaningful guarantee, and will simply increase friction.
like image 169
eggyal Avatar answered Feb 20 '23 02:02

eggyal