Data type
Comprehension
The bit width of the numeric types isize and usize depends on whether the system runs on a 32-bit or 64-bit architecture
Integer overflow panics in debug mode but not in release mode
wrapping_* methods avoid panics even in debug mode
checked_* methods return None on overflow
overflowing_* methods return a boolean indicating whether overflow occurred
saturating_* methods clamp the value to the minimum or maximum on overflow
tuple
let tup: (i32, f64, u8) = (500, 6.4, 1);
let tup = (500, 6.4, 1);
let (x, y, z) = tup; // destructuring assignment
let x: (i32, f64, u8) = (500, 6.4, 1);
let five_hundred = x.0;
let six_point_four = x.1;
let one = x.2;
array
let a = [1, 2, 3, 4, 5];
let a: [i32; 5] = [1, 2, 3, 4, 5];
let a = [0; 5]; // quick initialization
let a = [[0, 5]; 20]; // two-dimensional array
Origin
Scalar Types
…
Integer Types
Additionally, the isize and usize types depend on the kind of computer your program is running on: 64 bits if you’re on a 64-bit architecture and 32 bits if you’re on a 32-bit architecture.
…
Integer Overflow
Let’s say you have a variable of type u8 that can hold values between 0 and 255. If you try to change the variable to a value outside of that range, such as 256, integer overflow will occur. Rust has some interesting rules involving this behavior. When you’re compiling in debug mode, Rust includes checks for integer overflow that cause your program to panic at runtime if this behavior occurs. Rust uses the term panicking when a program exits with an error; we’ll discuss panics in more depth in the
“Unrecoverable Errors with panic!”
section in Chapter 9.
When you’re compiling in release mode with the --release flag, Rust does not include checks for integer overflow that cause panics. Instead, if overflow occurs, Rust performs two’s complement wrapping. In short, values greater than the maximum value the type can hold “wrap around” to the minimum of the values the type can hold. In the case of a u8, the value 256 becomes 0, the value 257 becomes 1, and so on. The program won’t panic, but the variable will have a value that probably isn’t what you were expecting it to have. Relying on integer overflow’s wrapping behavior is considered an error.
To explicitly handle the possibility of overflow, you can use these families of methods that the standard library provides on primitive numeric types:
- Wrap in all modes with the
wrapping_*methods, such aswrapping_add - Return the
Nonevalue if there is overflow with thechecked_*methods - Return the value and a boolean indicating whether there was overflow with the
overflowing_*methods - Saturate at the value’s minimum or maximum values with
saturating_*methods