typestar

distinct types in Odin

Celsius and Fahrenheit share a layout but refuse to mix — distinct mints new types.

package main

import "core:fmt"

// distinct mints a new type: same layout, no accidental mixing.
Celsius :: distinct f32
Fahrenheit :: distinct f32

to_fahrenheit :: proc(c: Celsius) -> Fahrenheit {
    return Fahrenheit(f32(c) * 9.0 / 5.0 + 32.0)
}

main :: proc() {
    cabin := Celsius(21.5)
    // to_fahrenheit(Fahrenheit(70)) would refuse to compile.
    fmt.printfln("cabin: %.1f C = %.1f F", f32(cabin),
        f32(to_fahrenheit(cabin)))
}

How it works

  1. Celsius :: distinct f32 is a full type, not an alias.
  2. The converter takes Celsius and returns Fahrenheit, casts spelled out.
  3. Feeding it a Fahrenheit is a compile error, which is the entire point.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
425
Tokens
80
Three-star pace
65 tpm

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

Type this snippet

Step 1 of 3 in Types & generics, step 19 of 27 in Language basics.

← Previous Next →