Rust Array Methods With Examples

What Are Array Methods in Rust?

Rust provides us with ready-made functions that can be used in arrays. These methods make it easier in multiple things, like:

  • Check properties → It can find how many items are in the array.
  • Loop or iterate → It goes through each element safely.
  • Transform → create new results from the array without changing ownership rules.

These methods ensure safety and efficiency by leveraging Rust’s ownership and borrowing rules.

Array Methods in Rust

Below is a detailed explanation of the most commonly used array methods in Rust.

  • .len()
  • .is_empty()
  • .first()
  • .last()
  • .get()
  • .iter()
  • .as_slice()
  • .contains()
  • .clone()
  • .split_at()

1) .len()

The .len() method in Rust tells you how many elements are inside an array.

Arrays in Rust have a fixed size. len () just returns that size directly without doing any extra calculation.

This is very useful when you want to know the size of the array instead of counting elements manually.

Example:

fn main() {
let cities = ["Delhi", "Mumbai", "Chennai", "Kolkata"];

println!("We have {} cities in the list.", cities.len());

// Using len() inside a condition
if cities.len() > 3 {
println!("That's a long list of cities!");
} else {
println!("Only a few cities are listed.");
}
}

Output:

We have 4 cities in the list.
That's a long list of cities!

2) .is_empty()

The .is_empty() method in Rust is used to check if an array has no elements. Arrays are always fixed in size; this method will only return true if the array length is zero, otherwise it returns false.

Example:

fn main() {
let scores: [i32; 0] = []; // an empty array
let marks = [10, 20, 30]; // a non-empty array

println!("Is 'scores' empty? {}", scores.is_empty());
println!("Is 'marks' empty? {}", marks.is_empty());

// Using is_empty() in a real check
if marks.is_empty() {
println!("No marks available.");
} else {
println!("Marks are recorded successfully.");
}
}

Output:

Is 'scores' empty? true
Is 'marks' empty? false
Marks are recorded successfully.

3) .first()

The .first() method in Rust is used when you want to safely get the first element of an array.

  • If the array has at least one element, it will return Some(value).
  • If the array is empty, it will return None.

Example:

fn main() {
let animals = ["Dog", "Cat", "Elephant"];
let empty: [i32; 0] = []; // empty array

// Case 1: Non-empty array
if let Some(first_animal) = animals.first() {
println!("The first animal is: {}", first_animal);
}

// Case 2: Empty array
match empty.first() {
Some(num) => println!("First number: {}", num),
None => println!("The array is empty, no first element."),
}
}

Output:

The first animal is: Dog
The array is empty, no first element.

4) .last()

The .last() method returns the last element of the array.

  • If the array has elements, it returns Some(value) with the last one.
  • If the array is empty, it returns None.

This makes your program safe because you don’t have to worry about crashes when the array has no data.

Example:

fn main() {
let numbers = [5, 15, 25, 35];
let empty: [i32; 0] = []; // an empty array

// Case 1: Non-empty array
if let Some(last_num) = numbers.last() {
println!("The last number is: {}", last_num);
}

// Case 2: Empty array
match empty.last() {
Some(value) => println!("Last value: {}", value),
None => println!("The array is empty, so no last element."),
}
}

Output:

The last number is: 35
The array is empty, so no last element.

5) .get()

The .get(index) method in Rust is used to access an element by its index.

  • If the index is valid, it returns Some(value) with the element.
  • If the index is invalid (out of bounds), it returns None instead of crashing the program.

Example:

fn main() {
let fruits = ["Apple", "Banana", "Mango"];

// Safe access with valid index
if let Some(fruit) = fruits.get(2) {
println!("Fruit at index 2: {}", fruit);
}

// Safe access with invalid index
match fruits.get(5) {
Some(fruit) => println!("Fruit at index 5: {}", fruit),
None => println!("No fruit found at this index."),
}
}

Output:

Fruit at index 2: Mango
No fruit found at this index.

6) .iter()

The .iter() method in Rust is used when you want to go through each element of an array one by one.

  • It does not take ownership of the array, it only borrows the elements.
  • This means you can still use the array after looping.

Example:

fn main() {
let cities = ["Delhi", "Mumbai", "Chennai"];

println!("List of cities:");
for city in cities.iter() {
println!("- {}", city);
}

// Proof that array is still usable after iteration
println!("Total cities: {}", cities.len());
}

Output:

List of cities:
- Delhi
- Mumbai
- Chennai
Total cities: 3

7) .as_slice()

The .as_slice() method is used to view an array as a slice.

  • .as_slice() does not copy the array.
  • It just gives you a borrowed reference to the entire array in the form of a slice (&[T]).

Example:

fn main() {
let fruits = ["Apple", "Banana", "Mango"];

// Convert array to slice
let fruit_slice = fruits.as_slice();

println!("Slice of fruits: {:?}", fruit_slice);

// You can still access like a normal array
println!("First fruit from slice: {}", fruit_slice[0]);
}

Output:

Slice of fruits: ["Apple", "Banana", "Mango"]
First fruit from slice: Apple

8) .contains()

The .contains(&value) method is used to check if a specific value exists inside an array.

Example:

fn main() {
let colors = ["Red", "Green", "Blue"];

// Check if "Green" is inside the array
let has_green = colors.contains(&"Green");

// Check if "Yellow" is inside the array
let has_yellow = colors.contains(&"Yellow");

println!("Does the array contain Green? {}", has_green);
println!("Does the array contain Yellow? {}", has_yellow);
}

Output:

Does the array contain Green? true
Does the array contain Yellow? false

9) .clone()

The .clone() method is used to make a full copy of an array. The original array and the cloned array are completely separate. It means that changing one will not affect the other.

Think of it like photocopying a document; you have the same content, but two different papers.

Example:

fn main() {
let scores = [85, 90, 78];

// Create a clone of the scores array
let mut scores_copy = scores.clone();

// Modify the copy
scores_copy[0] = 100;

println!("Original scores: {:?}", scores);
println!("Modified copy: {:?}", scores_copy);
}

Output:

Original scores: [85, 90, 78]
Modified copy: [100, 90, 78]

10) .split_at()

The .split_at(mid) method is used to divide an array into two parts at the given index (mid).

  • The first part will include elements from the start up to mid-1.
  • The second part will include elements from mid till the end.

Think of it like cutting a pizza into two parts at one point; you don’t create a new pizza, you just divide it into two parts.

Example: Splitting a Week into Workdays and Weekend

fn main() {
let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

// Split after 5 elements (workdays)
let (workdays, weekend) = days.split_at(5);

println!("Workdays: {:?}", workdays);
println!("Weekend: {:?}", weekend);
}

Output:

Workdays: ["Mon", "Tue", "Wed", "Thu", "Fri"]
Weekend: ["Sat", "Sun"]

Mini Project: Student Marks Analyzer

We will create a small program that:

  • Stores students’ marks in an array.
  • Uses different array methods (len, is_empty, first, last, get, iter, as_slice, contains, clone, split_at).

Code Implementation:

fn main() {
// Step 1: Store marks of students
let marks = [85, 92, 76, 88, 95];

// .len() → Find total students
println!("Total students: {}", marks.len());

// .is_empty() → Check if array is empty
println!("Is marks list empty? {}", marks.is_empty());

// .first() → First student's marks
if let Some(first) = marks.first() {
println!("First student's marks: {}", first);
}

// .last() → Last student's marks
if let Some(last) = marks.last() {
println!("Last student's marks: {}", last);
}

// .get() → Safe access (e.g. 3rd student)
match marks.get(2) {
Some(value) => println!("3rd student's marks: {}", value),
None => println!("No student at this index"),
}

// .iter() → Print all marks one by one
println!("All students' marks:");
for m in marks.iter() {
println!("{}", m);
}

// .as_slice() → Get slice of marks
let slice = marks.as_slice();
println!("Slice view of marks: {:?}", slice);

// .contains() → Check if anyone scored 100
println!("Did anyone score 100? {}", marks.contains(&100));

// .clone() → Make a copy of marks
let marks_copy = marks.clone();
println!("Copied marks list: {:?}", marks_copy);

// .split_at() → Split into first half and second half
let (first_half, second_half) = marks.split_at(2);
println!("First half of students: {:?}", first_half);
println!("Second half of students: {:?}", second_half);
}

Output:

Total students: 5
Is marks list empty? false
First student's marks: 85
Last student's marks: 95
3rd student's marks: 76
All students' marks:
85
92
76
88
95
Slice view of marks: [85, 92, 76, 88, 95]
Did anyone score 100? false
Copied marks list: [85, 92, 76, 88, 95]
First half of students: [85, 92]
Second half of students: [76, 88, 95]

Your Exercise: Student Attendance Tracker

We will create a simple program that:

  • Stores the attendance (P = Present, A = Absent) of students in an array.
  • Uses array methods like len, is_empty, first, last, contains, iter, and split_at to analyze attendance.

Write a Rust program that:

  1. Stores the attendance of 7 days in an array. Example: [“P”, “A”, “P”, “P”, “A”, “P”, “P”].
  2. Prints the total number of days recorded using .len().
  3. Checks if the array is empty with .is_empty().
  4. Prints the first and last day’s attendance using .first() and .last().
  5. Checks if the student was ever absent using .contains(&”A”).
  6. Iterates over the array with .iter() to print each day’s record.

Learn Other Topics About Rust Programming

Leave a Comment