Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Rust Arrays

An array holds a fixed number of values, all of the same type, one after another. The seven days of a week, the twelve months of a year, the scores of a team of eleven: when the number of items is known and never changes, an array is a good fit.

fn main() {
    let marks = [78, 92, 65, 88, 70];
    println!("First mark: {}", marks[0]);
    println!("Last mark: {}", marks[4]);
    println!("Number of marks: {}", marks.len());
}
Output
First mark: 78
Last mark: 70
Number of marks: 5

You reach an item by its index in square brackets. Like almost every programming language, Rust starts counting at 0, so the first item is marks[0] and the fifth is marks[4].

Arrays of one value, and the type

To make an array where every item starts with the same value, write the value, a semicolon and the length. The type of an array is written the same way: [i32; 5] means "five i32 numbers".

fn main() {
    let mut seats: [bool; 6] = [false; 6];
    seats[2] = true;
    seats[3] = true;
    println!("{:?}", seats);
}
Output
[false, false, true, true, false, false]

To change an item, the array must be mut. {:?} prints the whole array, which is handy while you are building a program.

Looping over an array

A for loop visits every item, and arrays have useful methods of their own:

fn main() {
    let rainfall = [12, 0, 7, 25, 3, 0, 18];
    let mut total = 0;
    for mm in rainfall {
        total += mm;
    }
    println!("Total rainfall: {} mm", total);
    println!("Wettest day: {} mm", rainfall.iter().max().unwrap());
    println!("Dry days: {}", rainfall.iter().filter(|&&mm| mm == 0).count());
    println!("Any storm? {}", rainfall.contains(&25));
}
Output
Total rainfall: 65 mm
Wettest day: 25 mm
Dry days: 2
Any storm? true

Rust checks every index

What if you ask for marks[10] in a list of five? In some languages, the program quietly reads whatever memory happens to be there, which leads to strange bugs and security holes. Rust always checks. If it can see the problem while compiling, it refuses to build. If the index is only known while running, the program stops with a clear message instead, saying the index is out of bounds. This is called a panic, and you will learn more about it in its own topic.

Arrays cannot grow or shrink. When you need a list whose length changes, for example a shopping list that you keep adding to, use a vector, which is next.

Practice exercises

  1. Make an array of the 12 month lengths and print the total number of days in a year.
  2. Find the position of the highest mark in an array using a loop with enumerate.
  3. Create an array of 10 zeros, set every second item to 1, and print it with {:?}.