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
Celsius :: distinct f32is a full type, not an alias.- The converter takes
Celsiusand returnsFahrenheit, casts spelled out. - Feeding it a
Fahrenheitis a compile error, which is the entire point.
Keywords and builtins used here
CelsiusFahrenheitdistinctf32importpackageprocreturn
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.
Step 1 of 3 in Types & generics, step 19 of 27 in Language basics.