Menu
Coddy logo textTech

Array Methods

Part of the Fundamentals section of Coddy's Rust journey — lesson 61 of 75.

Arrays are packed with many methods (functionalities). To access a method, write:

array.methodName(otherParameters)

Here is a list of the basic methods:

  • len() - returns the number of elements in the array
  • contains(value) - checks if the array contains a specific value
  • is_empty() - checks if the array is empty
  • reverse() - Reverses the array

For example:

let numbers = [10, 20, 30, 40, 50];
let length = numbers.len();
println!("Length: {}", length);

numbers.reverse()
// [50, 40, 30, 20, 10]

Example of the is_empty() method:

let numbers: [i32; 0] = [];
let empty = numbers.is_empty();
println!("Is empty: {}", empty);

This will output:

Is empty: true

When using contains, you need to pass a reference to the value you're looking for using &. For example:

let numbers = [10, 20, 30, 40, 50];
let has_thirty = numbers.contains(&30);
println!("Contains 30: {}", has_thirty);
// Output: Contains 30: true
challenge icon

Challenge

Easy

Create a function named analyze_array that receives an array of strings of size 5 as an argument. The method should perform the following operations:

  1. Check if the array is empty using the is_empty() method and print the result.
  2. Check if the array contains the string “5” using the contains() method and print the result. Remember to use String and not str: “5”.to_string()
  3. Reverse the array and print it

The output should follow this exact format:

Is empty: [true or false]
Contains 5: [true or false]
Reversed Elements:
[element1]
[element2]
...

Cheat sheet

Arrays have built-in methods accessed with dot notation:

array.methodName(otherParameters)

Basic array methods:

  • len() - returns the number of elements
  • contains(value) - checks if array contains a specific value
  • is_empty() - checks if array is empty
  • reverse() - reverses the array

Examples:

let numbers = [10, 20, 30, 40, 50];
let length = numbers.len();
let has_thirty = numbers.contains(&30);
let empty = numbers.is_empty();
numbers.reverse(); // [50, 40, 30, 20, 10]

Note: contains() requires a reference to the value using &.

Try it yourself

use std::io;
use std::convert::TryInto;

fn analyze_array(arr: &mut [String; 5]) {
    // Write code here




    // Print elements line by line
    for element in arr.iter() {
        println!("{}", element);
    }
}

fn main() {
    let mut input_str_arr = String::new();
    io::stdin().read_line(&mut input_str_arr).unwrap();
    let mut arr: [String; 5] = input_str_arr.split(',').map(String::from).collect::<Vec<String>>().try_into().unwrap();
    analyze_array(&mut arr);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals