typestar

Unions in Odin

One reading, two shapes: a temperature when the sensor works, a reason when not.

package main

import "core:fmt"

// One variant at a time: a temperature, or the reason there is none.
Reading :: union { f32, string }

report :: proc(r: Reading) {
    switch v in r {
    case f32:
        fmt.printfln("steady at %.1f C", v)
    case string:
        fmt.println("sensor down:", v)
    }
}

main :: proc() {
    report(Reading(f32(21.5)))
    report(Reading("loose wire"))
}

How it works

  1. Reading :: union { f32, string } holds one variant and remembers which.
  2. switch v in r is the type switch: each case gets the payload typed.
  3. Reading(f32(21.5)) constructs a variant with an explicit conversion.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
352
Tokens
85
Three-star pace
65 tpm

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

Type this snippet

Step 3 of 3 in Structs, enums & unions, step 15 of 27 in Language basics.

← Previous Next →

Unions in other languages