< All Blog

Integer Literals Suffix in Rust

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 from 0 to 2^8-1 = 255, meaning uint8 cannot represent number 256 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();

Recommended Posts

  1. How to Initialize Vector in Rust

    November 12, 2022
    In Rust, there are a couple of ways to initialize Vector. Vec::new() Vec::new() returns an empty vector. You can initialize a new empty vector and then pushing…
  2. Tuple with a Single Value in Rust

    November 11, 2022
    In Rust, tuples can be used to have different types of values as a container. Array does not allow you to have different types of elements instead. When Tuple …