Rust Fundamentals · 20 XP Pro

Arrays

An array holds a fixed number of values of the same type. Its type records both the element type and the length: [i32; 5] is five i32s. The length is part of the type and can never change.

let scores: [i32; 3] = [10, 20, 30];
let zeros = [0; 4];            // [0, 0, 0, 0]
let second = scores[1];        // 20 (indexing starts at 0)
println!("{}", scores.len());  // 3

Indexing out of bounds, like scores[3], panics at runtime rather than reading random memory.

Use for to visit each element in order. Arrays of Copy types such as integers can be passed to functions by value:

let mut total = 0;
for value in scores {
    total += value;
}

To change elements, declare the array mut and assign with an index: scores[0] = 99;. A for i in 0..scores.len() loop gives you the positions if you need them.

Your task

This chapter's capstone. All functions take arrays of exactly five i32s.

  • sum(values: [i32; 5]) -> i32: add all the elements.
  • largest(values: [i32; 5]) -> i32: the biggest element. Start from the first one and compare the rest.
  • reversed(values: [i32; 5]) -> [i32; 5]: a new array with the elements in the opposite order. Start with let mut out = [0; 5]; and fill it by index.

Next lesson →

Sign in to run your code. It's free.