Understanding Data Types in Rust
Introduction
Rust is a statically typed language with a rich set of built-in data types. Understanding these types is crucial for writing efficient and correct Rust programs.
Numeric Types
Integer Types
Rust provides several integer types with different sizes and signedness:
Size | 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 |
> Note: isize
and usize
types are platform-dependent. They're 32 bits on 32-bit systems and 64 bits on 64-bit systems.
Integer Literals
Integers can be written in various formats:
Base | Example | Description |
---|---|---|
Decimal | 98_222 | Underscores can be used for readability |
Hex | 0xff | Prefix with 0x |
Octal | 0o77 | Prefix with 0o |
Binary | 0b1111_0000 | Prefix with 0b |
Byte | b'A' | Only for u8 type |
Floating-Point Types
Rust supports two floating-point types:
f32
: 32-bit float (single precision)f64
: 64-bit float (double precision, default)
fn main() {
let x = 2.0; // f64 by default
let y: f32 = 3.0; // f32 explicitly
}
Mathematical Operations
Basic Arithmetic
fn main() {
// Addition
let sum = 5 + 10;
// Subtraction
let difference = 95.5 - 4.3;
// Multiplication
let product = 4 * 30;
// Division
let quotient = 56.7 / 32.2;
// Remainder (modulo)
let remainder = 43 % 5;
}
Compound Assignment Operators
let mut sum = 5;
sum += 1; // Equivalent to: sum = sum + 1
> Note: Rust doesn't support ++
or --
operators to maintain code clarity and explicit value changes.
Boolean Type
The boolean type (bool
) has two possible values:
let t = true;
let f: bool = false;
Character Type
Rust's char
type is 4 bytes and represents a Unicode scalar value:
let c = 'z';
let emoji = '😀';
let chinese = 'ä¸';
> Important: Rust char
s are Unicode scalar values (U+0000 to U+D7FF and U+E000 to U+10FFFF). For text handling, it's recommended to use strings (UTF-8) instead of individual chars, especially for non-ASCII text.
Compound Types
Tuples
Tuples group multiple values of different types:
// Explicit type annotation
let tup: (i32, f64, u8) = (500, 6.4, 1);
// Access via dot notation
let x = tup.0; // 500
let y = tup.1; // 6.4
let z = tup.2; // 1
// Destructuring
let (a, b, c) = tup;
// Now b equals 6.4
Arrays
Arrays are fixed-length collections of same-type elements:
// Integer array
let numbers = [1, 2, 3, 4, 5];
// String array
let months = ["January", "February", "March"];
// Type and length annotation
let array: [i32; 5] = [1, 2, 3, 4, 5];
// Repeated value initialization
let zeros = [0; 5]; // Creates [0, 0, 0, 0, 0]
// Array access
let first = numbers[0];
let second = numbers[1];
// Mutable array
let mut mutable_array = [1, 2, 3];
mutable_array[0] = 4; // Valid modification
Best Practices
-
Type Selection
- Use
i32
for general integers (good balance of range and performance) - Use
f64
for floating-point calculations (modern CPUs handle it as efficiently asf32
) - Use
usize
for array indices and size calculations
- Use
-
Unicode Handling
- Prefer
String
overchar
for non-ASCII text - Always use UTF-8 encoding for source files containing non-ASCII characters
- Prefer
-
Array Usage
- Use arrays when you know the size won't change
- Consider
Vec<T>
(vector) for dynamic size requirements
-
Numeric Operations
- Be explicit about type conversions to avoid runtime errors
- Use underscores in large numbers for readability:
1_000_000
Common Pitfalls
-
Integer Overflow
let x: u8 = 255; // let y = x + 1; // Panics in debug mode, wraps in release mode
-
Floating-Point Precision
let x = 0.1 + 0.2; // println!("{}", x == 0.3); // Might be false due to floating-point precision
-
Array Bounds
let arr = [1, 2, 3]; // let element = arr[3]; // Panics: index out of bounds
Next Steps
After understanding Rust's basic data types, you can explore:
- Collections (Vec, HashMap, etc.)
- Custom types with structs and enums
- Generic types
- Type conversions and casting
- Advanced string handling
Remember: Rust's type system is designed to prevent many common programming errors at compile time, making your programs more reliable.