Nimony

The road to Nim 3

result

nimony/lib/std/result.nim

result — a success-or-error sum type built on Nimony's native sum types.

Result[T, E] holds exactly one of Ok (the value, type T) or Err (the error, type E).

ok(v) / err(e) infer the parameter their argument does not fix from the call's expected type, so an annotated target (a typed result, let, proc return, etc.) is enough — result = ok(8080) in a Result[int, string] context binds E = string. Spell both out (ok[int, string](v)) only where there is no expected type to infer from.

unsafeGet raises BugError on the wrong variant (a system ErrorCode — calling it unguarded is a programming error); guard with isOk, or use the total get(default).

import std/result
proc parsePort(s: string): Result[int, string] =
  if s == "": result = err("empty")
  else: result = ok(8080)
let r = parsePort("80")
if r.isOk: echo r.get(0) else: echo r.error("?")