Rust Reference ยท Primitive Types
Rust unsigned integer types
Reference for Rust's unsigned integer types u8 to u128 and usize: ranges, subtraction underflow, byte literals, power-of-two helpers and indexing with usize.
The unsigned integer types are u8, u16, u32, u64, u128 and usize. They hold whole numbers from 0 up to 2^N - 1. usize is as wide as a pointer and is the type of lengths, indexes and size_of results; u8 is the byte type, used for raw data and ASCII.
Because there are no negative values, the classic bug is subtraction underflow: 3_u32 - 5 panics in debug builds and wraps to a huge number in release builds. Compare first, or use checked_sub, saturating_sub or abs_diff.
let byte: u8 = 255; let len: usize = "hello".len(); let flags = 0b1010_0001_u8;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
let n: u32 = 42; let m = 1_u64 << 40; let b = u8::try_from(300_i32); // Err(...) let parsed = "42".parse::<u16>(); // Ok(42)
| Type | Bits | Maximum |
|---|---|---|
u8 |
8 | 255 |
u16 |
16 | 65,535 |
u32 |
32 | 4,294,967,295 |
u64 |
64 | 18,446,744,073,709,551,615 |
u128 |
128 | about 3.4 x 10^38 |
usize |
pointer width | u64::MAX on 64-bit targets |
Common items: MIN (always 0), MAX, BITS, pow, abs_diff, div_ceil, is_power_of_two, next_power_of_two, count_ones, leading_zeros, trailing_zeros, rotate_left, swap_bytes, to_be_bytes, from_le_bytes, isqrt, ilog2, ilog10.
Panics: overflow and underflow (debug builds), division by zero (always), next_power_of_two overflow (debug builds), and ilog2(0) or ilog10(0).
Usage notes
- Use
usizefor indexes and lengths becauseVecand slices index with it. Convert from other widths withusize::try_from(n)whenncould be negative or too large. - Loops that count down over
usizeneed care:for i in (0..n).rev()is safe, whilewhile i >= 0is always true for unsigned types (the compiler warns). u8is also the byte of text and I/O:&[u8],Vec<u8>,b'x'andb"...".charis separate and 4 bytes; convert withu8 as char(ASCII/Latin-1 only).- Byte order:
to_be_bytes,to_le_bytes,to_ne_bytesand the matchingfrom_*_bytesgive explicit endianness, preferable to transmuting. - Bit manipulation shifts panic in debug builds if the shift amount is not less than
BITS; usechecked_shlorwrapping_shlotherwise. usizeis not portable in file formats. Storeu32oru64in serialized data, notusize.- Mixing signed and unsigned needs an explicit conversion;
aswraps,try_fromchecks.