Menu
Coddy logo textTech

Accessing Elements

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

Each value in an array is called an element, and each element has an index. The indices start from 0 to the length of the array minus one. For example take a look at the next array: 

let letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  • Element a is at index 0
  • Element b is at index 1
  • ...
  • Element g is at index 6

To access an element of an array, we can use its index within square brackets. For example, to access the first element of an array named letters, we would use letters[0].

Here's an example:

let numbers = [10, 20, 30, 40, 50];
let element = numbers[2];

The variable element will hold the value 30 because it accesses the third element (which has an index of 2).

challenge icon

Challenge

Easy

Create a function named values that receives an array as an argument and prints all of the items in the array one after the other.

To iterate over an array use the .len() field:

for i in 0..numbers.len() {
    // code
}

This way i will iterate from 0 to numbers.len() (not including) which is exactly all of the array indices.

Cheat sheet

Array elements are accessed using indices starting from 0:

let letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
let first_element = letters[0]; // 'a'
let third_element = letters[2]; // 'c'

To iterate over an array, use .len() to get the array length:

for i in 0..numbers.len() {
    // i goes from 0 to numbers.len() (exclusive)
}

Try it yourself

fn values(arr: &[i32]) {
    // Write code here
}

fn main() {
    let numbers = [10, 20, 30, 40, 50];
    values(&numbers);
}
quiz iconTest yourself

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

All lessons in Fundamentals