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
hauls: [dynamic]f32starts empty;defer delete(hauls)schedules the cleanup.append(&hauls, ...)takes a pointer and accepts several values at once.lenand indexing work like any array once the elements are in.
Keywords and builtins used here
appenddeferdeletedynamicf32importlenpackageproc
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.
Step 2 of 3 in Collections, step 11 of 27 in Language basics.