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
openreturns a value and aVault_Error;.Noneis the all-clear.open(628) or_returnforwards any non-zero error intoheist's own error slot.berths["Tern"] or_else 0supplies a fallback when the ok flag is false.
Keywords and builtins used here
NoneVault_ErrorWrong_Combinationdeferdeletedoenumifimportintmakemapor_elseor_returnpackageprocreturnstring
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.
Step 2 of 3 in Idioms, step 17 of 27 in Language basics.