< All Blog
November 09, 2022
In Rust, a suffix for Integer literals indicates their type.
For example, all of the following is 10
, but with different integer types.
10_u8 // uint8
10_u16 // uint16
10_u32 // uint32
10_u64 // uint64
10_u128 // uint128
10_usize // usize
Let's imagine to add two integers. The following code is completely valid and returns 256 (= 1 + 255)
.
let result = 1_u16.checked_add(255_u16).unwrap();
println!("{}", result); //=> 256
However, the following code panicks because 256
is overflowed value in the uint8
range.
let result = 1_u8.checked_add(255_u8).unwrap();
println!("{}", result);
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:2:43
NOTE:
uint8
has a range from0
to2^8-1 = 255
, meaninguint8
cannot represent number256
for example.
Please note that _
(underscore) is not necessary. In Rust, _
(underscore) can be used to improve readability of integers, which are removed during compilation.
// Both lines are the ssame
let result = 1u8.checked_add(255u8).unwrap();
let result = 1_u8.checked_add(255_u8).unwrap();