In Rust, arrays are a fixed-size collection of elements of the same type.
Arrays are useful for storing a sequence of values where the size is known at compile time.
This tutorial will cover:
1. What Are Arrays in Rust?
An array in Rust is a fixed-size data structure that stores multiple values of the same type in contiguous memory.
Key Features:
- Fixed size.
- Elements are of the same type.
- Zero-based indexing.
2. Declaring and Initializing Arrays
Example: Declaring Arrays
fn main() { let numbers = [1, 2, 3, 4, 5]; // Array of 5 integers let names: [&str; 3] = ["Alice", "Bob", "Charlie"]; // Array with explicit type and size println!("{:?}", numbers); println!("{:?}", names); }
Example: Array with Default Values
You can initialize an array with the same value using [value; size].
fn main() { let zeros = [0; 5]; // Array of 5 zeros println!("{:?}", zeros); // Output: [0, 0, 0, 0, 0] }
3. Accessing Array Elements
You can access elements of an array using the index operator ([]). Note that Rust performs bounds checking to prevent accessing invalid indices.
Example: Accessing Elements
fn main() { let numbers = [10, 20, 30, 40, 50]; println!("First element: {}", numbers[0]); println!("Second element: {}", numbers[1]); }
Example: Out-of-Bounds Access
Accessing an invalid index will cause a runtime panic.
fn main() { let numbers = [1, 2, 3]; // println!("{}", numbers[3]); // Uncommenting this line will cause a panic }
4. Iterating Through Arrays
Example: Using for Loop
fn main() { let numbers = [10, 20, 30, 40, 50]; for number in numbers { println!("{}", number); } }
Example: Using enumerate
The enumerate method provides both the index and the value.
fn main() { let numbers = [10, 20, 30, 40, 50]; for (index, value) in numbers.iter().enumerate() { println!("Index: {}, Value: {}", index, value); } }
5. Common Array Methods
Rust arrays implement some commonly used methods through the std::slice trait.
Example: Length of an Array
fn main() { let numbers = [1, 2, 3, 4, 5]; println!("Length of array: {}", numbers.len()); }
Example: Check if Array Is Empty
fn main() { let numbers: [i32; 0] = []; println!("Is the array empty? {}", numbers.is_empty()); }
Example: Slicing an Array
You can create a slice (a reference to part of an array).
fn main() { let numbers = [1, 2, 3, 4, 5]; let slice = &numbers[1..4]; // Slice containing elements from index 1 to 3 println!("{:?}", slice); // Output: [2, 3, 4] }
6. Multidimensional Arrays
Rust supports arrays with more than one dimension.
Example: Declaring and Accessing a 2D Array
fn main() { let matrix: [[i32; 3]; 2] = [ [1, 2, 3], [4, 5, 6], ]; println!("Matrix: {:?}", matrix); println!("Element at (1, 2): {}", matrix[1][2]); // Access row 1, column 2 }
7. Arrays and Functions
You can pass arrays to functions by reference or by value.
Example: Passing an Array to a Function
fn print_array(arr: &[i32]) { for &value in arr { println!("{}", value); } } fn main() { let numbers = [10, 20, 30, 40, 50]; print_array(&numbers); // Pass a slice of the array }
Example: Returning an Array from a Function
fn create_array() -> [i32; 3] { [1, 2, 3] } fn main() { let array = create_array(); println!("{:?}", array); }
8. Practical Examples
8.1 Summing Elements in an Array
fn main() { let numbers = [10, 20, 30, 40, 50]; let sum: i32 = numbers.iter().sum(); println!("Sum of elements: {}", sum); }
8.2 Finding the Largest Element
fn main() { let numbers = [3, 1, 4, 1, 5, 9]; let max = numbers.iter().max().unwrap(); println!("Largest element: {}", max); }
8.3 Reversing an Array
fn main() { let numbers = [1, 2, 3, 4, 5]; let reversed: Vec<i32> = numbers.iter().rev().cloned().collect(); println!("Reversed array: {:?}", reversed); }
8.4 Initializing a 2D Array
fn main() { let mut grid = [[0; 3]; 3]; // 3x3 array initialized with zeros // Fill with values for i in 0..3 { for j in 0..3 { grid[i][j] = i + j; } } println!("Grid: {:?}", grid); }
9. Arrays vs Vectors
Feature | Array | Vector |
---|---|---|
Size | Fixed at compile time. | Dynamic, can grow or shrink. |
Memory | Stored on the stack. | Stored on the heap. |
Use Case | Use when size and type are known at compile time. | Use when size is unknown or changes at runtime. |
10. Summary
Key Features of Arrays in Rust
- Fixed-size collections of elements of the same type.
- Access elements using zero-based indexing.
- Slicing allows working with parts of the array.
- Suitable for static-sized data structures.
Common Use Cases
- Storing fixed-size sequences.
- Multidimensional data like grids or matrices.
- Efficient computation on small, fixed-size collections.
Experiment with these examples to master arrays in Rust