Rust Arrays
Fixed-size collections of elements
📊 What are Rust Arrays?
Arrays in Rust are fixed-size collections of elements of the same type stored in contiguous memory. They have compile-time known size, making them stack-allocated and very efficient for scenarios where collection size is predetermined and unchanging.
fn main() {
// Array with explicit type and size
let numbers: [i32; 5] = [1, 2, 3, 4, 5];
// Array with inferred type
let fruits = ["apple", "banana", "orange"];
println!("First number: {}", numbers[0]);
println!("Second fruit: {}", fruits[1]);
}
Output:
First number: 1
Second fruit: banana
Array Characteristics
Fixed Size
Size determined at compile time
let arr: [i32; 5] = [1,2,3,4,5];
Same Type
All elements must be the same type
let nums = [10, 20, 30];
Stack Allocated
Stored on the stack for performance
let fast_array = [1; 1000];
Index Access
Access elements by index
let first = arr[0];
🔹 Creating Arrays
Different ways to create arrays in Rust:
fn main() {
// Explicit type and size
let numbers: [i32; 4] = [1, 2, 3, 4];
// Type inferred from values
let colors = ["red", "green", "blue"];
// Initialize with same value
let zeros = [0; 5]; // [0, 0, 0, 0, 0]
// Mixed initialization
let mixed: [f64; 3] = [1.1, 2.2, 3.3];
println!("Numbers: {:?}", numbers);
println!("Colors: {:?}", colors);
println!("Zeros: {:?}", zeros);
println!("Mixed: {:?}", mixed);
}
Output:
Numbers: [1, 2, 3, 4]
Colors: ["red", "green", "blue"]
Zeros: [0, 0, 0, 0, 0]
Mixed: [1.1, 2.2, 3.3]
🔹 Accessing Array Elements
Access and modify array elements using indices:
fn main() {
let mut scores = [85, 90, 78, 92, 88];
// Access elements
println!("First score: {}", scores[0]);
println!("Last score: {}", scores[4]);
// Modify elements (array must be mutable)
scores[2] = 95; // Change third score
println!("Updated third score: {}", scores[2]);
// Get array length
println!("Number of scores: {}", scores.len());
// Safe access with get() method
match scores.get(10) {
Some(score) => println!("Score at index 10: {}", score),
None => println!("No score at index 10"),
}
}
Output:
First score: 85
Last score: 88
Updated third score: 95
Number of scores: 5
No score at index 10
🔹 Iterating Over Arrays
Different ways to loop through array elements:
fn main() {
let fruits = ["apple", "banana", "cherry", "date"];
// Method 1: Direct iteration
println!("Method 1 - Direct iteration:");
for fruit in fruits {
println!(" {}", fruit);
}
// Method 2: Using iter()
println!("\nMethod 2 - Using iter():");
for fruit in fruits.iter() {
println!(" {}", fruit);
}
// Method 3: With index using enumerate()
println!("\nMethod 3 - With index:");
for (index, fruit) in fruits.iter().enumerate() {
println!(" {}: {}", index, fruit);
}
// Method 4: Index-based loop
println!("\nMethod 4 - Index-based:");
for i in 0..fruits.len() {
println!(" fruits[{}] = {}", i, fruits[i]);
}
}
Output:
Method 1 - Direct iteration:
apple
banana
cherry
date
Method 2 - Using iter():
apple
banana
cherry
date
🔹 Array Methods and Operations
Useful methods and operations on arrays:
fn main() {
let numbers = [3, 1, 4, 1, 5, 9, 2, 6];
// Length
println!("Length: {}", numbers.len());
// Check if empty
println!("Is empty: {}", numbers.is_empty());
// First and last elements
println!("First: {:?}", numbers.first());
println!("Last: {:?}", numbers.last());
// Contains element
println!("Contains 5: {}", numbers.contains(&5));
println!("Contains 10: {}", numbers.contains(&10));
// Slicing
let slice = &numbers[2..5]; // Elements from index 2 to 4
println!("Slice [2..5]: {:?}", slice);
// Reverse iteration
println!("Reversed:");
for num in numbers.iter().rev() {
print!("{} ", num);
}
println!();
}
Output:
Length: 8
Is empty: false
First: Some(3)
Last: Some(6)
Contains 5: true
Contains 10: false
Slice [2..5]: [4, 1, 5]
Reversed:
6 2 9 5 1 4 1 3