typestar

or_return and or_else in Odin

Odin's error idiom: errors are ordinary values, and two operators shorten the plumbing.

package main

import "core:fmt"

Vault_Error :: enum {
    None,
    Wrong_Combination,
}

open :: proc(guess: int) -> (prize: string, err: Vault_Error) {
    if guess == 628 do return "deed to the tin mine", .None
    return "", .Wrong_Combination
}

// or_return forwards a non-zero error to this proc's own error slot.
heist :: proc() -> Vault_Error {
    prize := open(628) or_return
    fmt.println("inside:", prize)
    return .None
}

main :: proc() {
    if heist() == .None do fmt.println("clean getaway")
    // or_else supplies a fallback when the ok flag is false.
    berths := make(map[string]int)
    defer delete(berths)
    berths["Skua"] = 4
    spot := berths["Tern"] or_else 0
    fmt.println("unknown ships anchor at", spot)
}

How it works

  1. open returns a value and a Vault_Error; .None is the all-clear.
  2. open(628) or_return forwards any non-zero error into heist's own error slot.
  3. berths["Tern"] or_else 0 supplies a fallback when the ok flag is false.

Keywords and builtins used here

The run, in numbers

Lines
30
Characters to type
691
Tokens
150
Three-star pace
65 tpm

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

Type this snippet

Step 2 of 3 in Idioms, step 17 of 27 in Language basics.

← Previous Next →