Skip to content
Kavachकवच

Lists: Reading by index

● Beginner3 min

list[i] reads the item at position i, counting from 0; list.get(i) gives none instead of stopping.

fn main() {
    const names = ["Asha", "Ravi", "Meena"]
    print(names[0])
    print(names[2])
    print(names.get(5) ?? "nobody")
    print(names.len())
}

The program ran and printed:

kavach run index.kav

AshaMeenanobody3
index.kav: Kavach code, then what running it prints

names[5] on a three-item list can never work. When the compiler can see that, with a list written out and a number for the index, it refuses the program:

fn main() {
    const names = ["Asha", "Ravi", "Meena"]
    print(names[5])
}

The compiler refused the program:

kavach run index-past.kav

error: this always panics: index 5 is out of range: the list has 3 items (spec 1.8)
index-past.kav: Kavach code, then what running it prints

When the index is worked out while the program runs, the same mistake stops the program with a clear message instead. When a position may be past the end, get gives an optional, and ?? picks what to use then. first() and last() work the same way:

fn main() {
    const xs = [3, 1, 4]
    print(xs[0])
    print(xs.first() ?? 0)
    print(xs.last() ?? 0)
    print(xs.contains(4))
}

The program ran and printed:

kavach run read.kav

334true
read.kav: Kavach code, then what running it prints