Dynamic Arrays & Slices

📦 Slices, Dynamic Arrays & Fixed Arrays in Odin

Odin offers three distinct contiguous data container types: Fixed Arrays ([N]T), Slices ([]T), and Dynamic Arrays ([dynamic]T).


📊 1. Memory Layout Comparison

1. Fixed Array: [3]f32
   [ Float 0 ][ Float 1 ][ Float 2 ]  (Value type, stack or embedded)

2. Slice: []f32
   [ rawptr data ] [ int len ]        (Fat pointer view into external memory)

3. Dynamic Array: [dynamic]f32
   [ rawptr data ] [ int len ] [ int cap ] [ Allocator allocator ]
Type Syntax Header Size Heap Allocation Capacity Growth
Fixed Array [16]int 16×size_of(T) No (Inline) Fixed at compile time
Slice []int 16 bytes (ptr + len) No (Points to existing buffer) Fixed length view
Dynamic Array [dynamic]int 40 bytes (ptr + len + cap + alloc) Yes (via allocator) Automatic exponential realloc

âš¡ 2. Practical Syntax & Idioms

package main

import "core:fmt"

main :: proc() {
    // 1. Fixed array with compile-time count
    fixed_points := [4]f32{10.0, 20.0, 30.0, 40.0}

    // 2. Slice windowing (zero copy, points to sub-range of array)
    sub_slice: []f32 = fixed_points[1:3] // Views elements 20.0, 30.0

    // 3. Dynamic array with reserved capacity (avoids realloc hitching)
    entities: [dynamic]int
    reserve(&entities, 256)
    defer delete(entities)

    append(&entities, 100)
    append(&entities, 200, 300) // Variadic append
    
    // Fast unordered removal (O(1) swap-and-pop)
    unordered_remove(&entities, 0)
}
Fast Removal with unordered_remove

Standard ordered_remove(&arr, index) shifts all trailing elements left (O(N)). If order does not matter (e.g. active bullets, particles), use unordered_remove(&arr, index) which swaps the target element with the last element and decrements length in O(1) time.