t27.aiРусский

Arrays

You will learn

How to declare an array, read an item, and which index is the last one.

An array type is the length in square brackets followed by the item type: [5]u8 is five unsigned bytes. The value lists the items in square brackets. Index 0 holds the item at the start, so in an array of 5 the last index is 4. A test reads an item with PRIMES[4]. Keep the declared length and the list in step: the checker in this browser does not catch a length that disagrees with the list.

Try it

Add a sixth prime to PRIMES, fix the length, and write an assert for index 5.

Open the interactive lesson →

t27 basics 7: an array and its indexes
t27 basics 7: an array and its indexes ↗

A t27 array drawn as a row of cells with their indexes, from the lesson spec. Lesson 7 of the t27 basics course.

specs/basics/07_arrays.t27

// SPDX-License-Identifier: Apache-2.0
; t27 basics, lesson 7: Arrays.
; An array has a length and a type, [5]u8, and its items are read by index from 0.

module basics_07_arrays;

pub const PRIMES : [5]u8 = [2, 3, 5, 7, 11];
pub const DIGITS : [3]str = ["zero", "one", "two"];

test indexes_start_at_zero {
    assert PRIMES[0] == 2;
    assert PRIMES[4] == 11;
    assert DIGITS[2] == "two";
}

Open the lesson's spec in the player ↗

All lessons