Rust - Basic - 02 - Data Type

Types de données

Compréhension

Le nombre de bits des types isize et usize dépend de l’architecture 32/64 bits.

En mode debug, un dépassement provoque un panic ; en mode release, non.

wrapping_* évite le panic en mode debug.

checked_* renvoie None en cas de dépassement.

overflowing_* renvoie un booléen indiquant le dépassement.

saturating_* limite la valeur au minimum ou au maximum.

tuple

let tup: (i32, f64, u8) = (500, 6.4, 1);

let tup = (500, 6.4, 1);
let (x, y, z) = tup;  // 解构赋值

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];  // 快速初始化
let a = [[0, 5]; 20];  // 二维数组

Origin

https://doc.rust-lang.org/book/ch03-02-data-types.html

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 as wrapping_add
  • Return the None value if there is overflow with the checked_* 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