typestar

Dynamic arrays in Odin

[dynamic] grows on append and gives the memory back through delete.

package main

import "core:fmt"

main :: proc() {
    // [dynamic] grows on append; delete returns the memory.
    hauls: [dynamic]f32
    defer delete(hauls)

    append(&hauls, 12.5)
    append(&hauls, 8.0)
    append(&hauls, 15.25, 6.75)

    fmt.println(len(hauls), "hauls logged")
    fmt.printfln("first %.2f, last %.2f", hauls[0], hauls[len(hauls) - 1])
}

How it works

  1. hauls: [dynamic]f32 starts empty; defer delete(hauls) schedules the cleanup.
  2. append(&hauls, ...) takes a pointer and accepts several values at once.
  3. len and indexing work like any array once the elements are in.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
330
Tokens
87
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 75 seconds.

Type this snippet

Step 2 of 3 in Collections, step 11 of 27 in Language basics.

← Previous Next →

Dynamic arrays in other languages