What Are Arrays in Rust?
An array in Rust is like a box with fixed slots. Each slot holds a value of the same type (like all integers, all floats, or all strings).
Arrays have a fixed size determined at compile time. It means their length cannot change during runtime.
All elements are kept in a continuous block of memory, so Rust can access them very fast using their index.
Arrays are useful when you already know exactly how many items you want to store.
Features of Rust Arrays
- Fixed Size: Once you decide how many elements an array will have, it can’t grow or shrink. For example, if you say the array has 5 elements, it will always stay 5.
- Same Data Type: All elements in an array must be of the same type.
- Zero-Based Indexing: Rust arrays also start with 0 index, the same as other languages.
- Efficient Access: Arrays are stored in continuous memory, so Rust can instantly jump to any element by its index.
Syntax of Arrays in Rust
You can declare an array using square brackets ([ ]) and specifying the type and size.
fn main() {
// An array of 4 fruits (all type &str)
let fruits: [&str; 4] = ["Apple", "Banana", "Mango", "Orange"];
// Print the whole array
println!("All fruits: {:?}", fruits);
// Access by index
println!("First fruit is: {}", fruits[0]);
println!("Last fruit is: {}", fruits[3]);
// Length of array
println!("Total fruits: {}", fruits.len());
}
Here:
- [“Apple”, “Banana”, “Mango”, “Orange”] → This is the actual list of values inside the array.
Default Values
In Rust, you can fill an array with the same value for all elements using this syntax:
fn main() {
// Create an array of size 6 where each element is "Hi"
let greetings = ["Hi"; 6];
// Print the full array
println!("Array: {:?}", greetings);
// Accessing some elements
println!("First element: {}", greetings[0]);
println!("Last element: {}", greetings[5]);
}
- [“Hi”; 6] → Put the value “Hi” in every position.
- The total number of positions is 6.
- So it becomes: [“Hi”, “Hi”, “Hi”, “Hi”, “Hi”, “Hi”].
Accessing Array Elements
You can access array elements using their index, enclosed in square brackets ([ ]).
fn main() {
let colors = ["Red", "Green", "Blue", "Yellow"];
println!("First color: {}", colors[0]); // "Red"
println!("Third color: {}", colors[2]); // "Blue"
}
- Note: If you try to access an index that is out of bounds, Rust will throw a runtime error, ensuring safety.
Iterating Over Arrays
Rust provides multiple ways to iterate through arrays:
Using a for Loop
fn main() {
let fruits = ["Mango", "Orange", "Grapes"];
for fruit in fruits {
println!("Fruit: {}", fruit);
}
}
- The loop takes each item from the array (“Mango”, “Orange”, “Grapes”) and prints it.
Using the .iter() Method
fn main() {
let fruits = ["Mango", "Orange", "Grapes"];
for fruit in fruits.iter() {
println!("Fruit: {}", fruit);
}
}
- .iter() lets you borrow each element instead of moving it.
- This means you can still use the fruits array later in your program because ownership is not taken away.
Array Operations In Rust
- Length of an Array
- Slicing an Array
- Modifying Arrays
1) Length of an Array
The .len() method tells how many elements are inside the array.
fn main() {
let cities = ["Delhi", "Mumbai", "Kolkata", "Chennai"];
println!("Total cities: {}", cities.len());
}
2) Slicing an Array
A slice is like taking a small piece (view) from the array without copying data. We use [start. .end], where start is included, but end is excluded.
fn main() {
let marks = [10, 20, 30, 40, 50];
let part = &marks[1..4];
println!("Selected slice: {:?}", part);
}
3) Modifying Arrays
If you declare the array as mut (mutable), you can change its values.
fn main() {
let mut numbers = [5, 6, 7];
numbers[0] = 50; // change first element
numbers[2] = 70; // change third element
println!("Updated numbers: {:?}", numbers);
}
Multidimensional Arrays
A multidimensional array refers to an array that contains other arrays. Think of it like a table with rows and columns.
fn main() {
let grid: [[i32; 3]; 2] = [
[1, 2, 3], // first row
[4, 5, 6], // second row
];
println!("{:?}", grid);
println!("Value at row 0, column 1: {}", grid[0][1]);
}
- [[i32; 3]; 2] → This means “2 rows, each row has 3 numbers”.
- grid[0][1] → Go to row 0 → then pick column 1 → that is 2.
Output:
[[1, 2, 3], [4, 5, 6]]
Value at row 0, column 1: 2
Practical Example: Calculating the Average
fn main() {
let scores = [10, 20, 30, 40, 50];
let total: i32 = scores.iter().sum(); // adds all elements
let avg = total as f32 / scores.len() as f32;
println!("Average score: {}", avg);
}
Output:

Exercise: Student Marks Analysis System
Task:
Write a Rust program that:
- Finds out which student scored the highest average.
- Stores marks of 5 subjects for each student in a 2D array.
- Calculates the total marks and average for each student.
Example Code
fn main() {
// 2D Array: rows = students, cols = subjects
let marks: [[i32; 5]; 3] = [
[75, 82, 91, 68, 89], // Student 1
[88, 79, 85, 92, 76], // Student 2
[90, 95, 87, 93, 99], // Student 3
];
let mut highest_avg = 0.0;
let mut topper_index = 0;
for (i, student) in marks.iter().enumerate() {
let total: i32 = student.iter().sum();
let avg = total as f32 / student.len() as f32;
println!("Student {} -> Total: {}, Average: {:.2}", i + 1, total, avg);
if avg > highest_avg {
highest_avg = avg;
topper_index = i;
}
}
println!("\nTopper is Student {} with an average of {:.2}", topper_index + 1, highest_avg);
}
Example Output
Student 1 -> Total: 405, Average: 81.00
Student 2 -> Total: 420, Average: 84.00
Student 3 -> Total: 464, Average: 92.80
Topper is Student 3 with an average of 92.80