The Integer Types
are available in signed and unsigned flavours, from 8 bits to 128
bits. The unsigned versions are: u8, u16, u32, u64 and u128.
The signed versions are: i8, i16, i32, i64 and i128.
Table 1 provides a list of available operators.
Table 1:Arithmetic operators
6.1.1Default type¶
If unspecified, an integer is of type i32:
let i = 15; // Default type: i32
i156.1.2Specifying the type¶
To set explicitly the integer type, we can either set it to the variable or the value:
let i: u8 = 27; // 8-bit unsigned integer
let j = 516i16; // 16-bit signed integer
(i, j)(27, 516)6.1.3Separator¶
For big literal numbers, the underscore can be used to ease reading:
let n = 1_000_000_000;
let m = 12_34_56;
(n, m)(1000000000, 123456)6.1.4Binary, octal and hexadecimal¶
Binary, octal and hexadecimal numbers can be defined using the appropriate
prefix (0b, 0o, 0x):
let bin = 0b0100_0001_1110;
let oct = 0o466;
let hex = 0x23ff_89c8;
(bin, oct, hex)(1054, 310, 603949512)6.1.5Size types¶
Two architecture dependent integer types exist to store sizes (e.g.: array sizes, string sizes). One is signed and the other unsigned:
let n: isize = -1;
let m: usize = 8000;
(n, m)(-1, 8000)6.1.6Character byte¶
A special notation exists to define a character byte, which is stored as a
plain 8-bit integer (u8):
let n = b'A';
n65The type of n will be u8.
6.1.7Operations¶
Examples of computing a remainder:
(11 % 3, -11 % 3, 11 % -3, -11 % -3)(2, -2, 2, -2)A division:
(11 / 3, -11 / 3, 11 / -3, -11 / -3)(3, -3, -3, 3)6.1.8Type related constants¶
Some constants are directly accessible on the primitive types: i8, i16, i32, i64, u8, u16, u32, u64.
Example for 8-bit unsigned integer:
println!("BITS: {}", u8::BITS);
println!("MIN: {}", u8::MIN);
println!("MAX: {}", u8::MAX);BITS: 8
MIN: 0
MAX: 255
Example for 32-bit unsigned integer:
println!("BITS: {}", u32::BITS);
println!("MIN: {}", u32::MIN);
println!("MAX: {}", u32::MAX);BITS: 32
MIN: 0
MAX: 4294967295
Example for 64-bit signed integer:
println!("BITS: {}", i64::BITS);
println!("MIN: {}", i64::MIN);
println!("MAX: {}", i64::MAX);BITS: 64
MIN: -9223372036854775808
MAX: 9223372036854775807