Indexing

Arrays provide a handy method, len(), which tells you how many items they contain. They also support an indexing operator. An array has a sequence of values, numbered 0, 1, 2, and up. Each of these numbers is known as the index. The indexing operator takes the index and gives you the value at its position. Note that, since indices start at 0, an array of size 5 would have indices 0, 1, 2, 3, and 4, but does not have index 5.

This program will print out all of the values in the array:

Press + to interact
fn main() {
let numbers: [i32; 5] = [2, 3, 8, 1, 9];
let mut i = 0;
while i < numbers.len() {
println!("numbers[{}] == {}", i, numbers[i]);
i += 1;
}
}

We can use indexing into an array to mutate it as well. For example, I can set the value at index 2 to 10 with:

numbers[2] = 10;

Exercise Add that line before the while loop. The code won’t compile; can you guess why before asking the compiler? Also, try to predict what the output of the program will be.

Exercise Write a function, sum, that will add all the values in an array. You can test it with:

Press + to interact
fn main() {
let numbers: [i32; 5] = [2, 3, 8, 1, 9];
assert_eq!(23, sum(numbers));
println!("Good job!");
}

Bonus: Modify that function so that it takes a reference to the array instead of the array itself.