Rust - Basic - 02 - Data Type
Data type
Comprehension
数字类型的 isize
and usize
的位数取决于运行系统的 32/64 位架构
debug 模式对整数溢出会 panic,release 模式不会
wrapping_*
可以在 debug 模式也不 panic
checked_*
可以在溢出时返回 None
overflowing_*
可以返回 boolean 值表示是否溢出
saturating_*
可以在溢出时将值限定为 最小/最大值
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
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
None
value 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