LEARN VOID / 06

Collections

Grow a list and work with its values.

Illustrative fragment — place this code inside a function. It is verified in an executable context, but the download is not a standalone program.

collections.voidDownload fragment
var scores: [i32] = []
scores.push(12)
scores.push(18)
scores.push(20)

var total = 0
for score in scores:
    total += score

Create an empty typed list

This fragment belongs inside a function. [i32] declares a growable list of integers. The empty literal needs that type context. Three push calls add scores 12, 18 and 20; the order of calls is their order in the list.

Total the scores

The loop visits each score and adds it to total, which ends at 50. The fragment has no entry function and prints nothing. It can be followed by return total in an integer-returning function; that is how its result is verified.

Choose sharing or fixed storage

Assigning a growable list shares its identity, so mutations are visible through aliases. A fixed array includes its size, such as [i32, 3], and copies its value storage. Readonly views retain their restrictions through elements. See dictionaries for key/value data.

Remove a score safely

list.pop() removes the last item and returns Ok(item). An empty list returns Err("empty list"), leaving it unchanged. Match the result to choose a useful fallback. A positive input is added as the latest score and then removed. Input 18 returns 18; zero or negative input leaves the list empty and returns the fallback zero.

recoverable-list.voidDownload source
func entry(latest_score: i32) -> i32:
    var scores: [i32] = []
    if latest_score > 0:
        scores.push(latest_score)
    return match scores.pop():
        Ok(var score): score
        Err(var reason): 0
Input 18Expected result 18

Look up an optional position

Both lists and fixed arrays offer get(index), returning result<T, string>. Negative indexes count from the end; an unavailable position returns Err("index out of range"). The fixed-array example uses zero as its missing-milestone fallback. Direct indexing retains checked runtime failure behavior.

fixed-array-get.voidDownload source
func entry(index: i32) -> i32:
    const milestones: [i32, 3] = [10, 20, 30]
    return match milestones.get(index):
        Ok(var milestone): milestone
        Err(var reason): 0
Input 1Expected result 20