Rust Data Types
Rust language includes the following basic data types:
Integer Types
Integer types, or simply integers, are categorized by their bit length and whether they are signed or unsigned:
| Bit Length | Signed | Unsigned |
|---|---|---|
| 8-bit | i8 | u8 |
| 16-bit | i16 | u16 |
| 32-bit | i32 | u32 |
| 64-bit | i64 | u64 |
| 128-bit | i128 | u128 |
| arch | isize | usize |
The isize and usize types are used to measure data size and their bit length depends on the target platform. For a 32-bit architecture, they use a 32-bit integer.
Integer representations include:
| Base | Example |
|---|---|
| Decimal | 98_222 |
| Hexadecimal | 0xff |
| Octal | 0o77 |
| Binary | 0b1111_0000 |
| Byte (only for u8) | b'A' |
Underscores in integers help readability when dealing with large numbers.
Floating-Point Types
Rust supports 32-bit (f32) and 64-bit (f64) floating-point numbers. By default, 64.0 represents a 64-bit float, as modern CPUs handle both types similarly, but 64-bit offers higher precision.
Example
fn main() {
let x = 2.0; // f64
let y: f32 = 3.0; // f32
}
Mathematical Operations
Demonstrating mathematical operations in a program:
Example
fn main() {
let sum = 5 + 10; // addition
let difference = 95.5 - 4.3; // subtraction
let product = 4 * 30; // multiplication
let quotient = 56.7 / 32.2; // division
let remainder = 43 % 5; // modulus
}
Operators followed by = perform self-assignment, e.g., sum += 1 is equivalent to sum = sum + 1.
Note: Rust does not support ++ and -- to maintain code readability and awareness of variable changes.
Boolean Type
The boolean type is represented by bool and can only be true or false.
Character Type
The character type is represented by char.
Rust's char type is 4 bytes and represents a Unicode scalar value, supporting non-English characters, emojis, and zero-width spaces.
Unicode values range from U+0000 to U+D7FF and U+E000 to U+10FFFF (inclusive). However, the concept of "character" in Unicode does not align with intuitive understanding, so it's recommended to use strings for UTF-8 text.
Note: Using Chinese strings in programming may lead to encoding issues (GBK vs. UTF-8). Rust requires strings and characters to be UTF-8 encoded, or the compiler will error.
Compound Types
Tuples are groups of data enclosed in ( ) and can contain different types:
Example
let tup: (i32, f64, u8) = (500, 6.4, 1);
// tup.0 equals 500
// tup.1 equals 6.4
// tup.2 equals 1
let (x, y, z) = tup;
// y equals 6.4
Arrays are homogeneous data enclosed in [ ]:
Example
let a = [1, 2, 3, 4, 5];
// a is an integer array of length 5
let b = ["January", "February", "March"];
// b is a string array of length 3
let c: [i32; 5] = [1, 2, 3, 4, 5];
// c is an i32 array of length 5
let d = [3; 5];
// equivalent to let d = [3, 3, 3, 3, 3];
let first = a[0];
let second = a[1];
// array access
a[0] = 123; // error: array a is immutable
let mut a = [1, 2, 3];
a[0] = 4; // correct