result: expose value/error in errorOr/valueOr

* fix error type as well
This commit is contained in:
Jacek Sieka 2022-01-11 11:01:06 +01:00 committed by zah
parent d2ae2889e8
commit 6ad35b876f
2 changed files with 15 additions and 7 deletions

View File

@ -815,15 +815,21 @@ template valueOr*[T: not void, E](self: Result[T, E], def: untyped): T =
## ```
let s = (self) # TODO avoid copy
if s.o: s.v
else: def
else:
when E isnot void:
template error: E {.used, inject.} = s.e
def
template errorOr*[T: not void, E](self: Result[T, E], def: untyped): E =
template errorOr*[T, E: not void](self: Result[T, E], def: untyped): E =
## Fetch error of result if not set, or evaluate `def`
## `def` is evaluated lazily, and must be an expression of `T` or exit
## the scope (for example using `return` / `raise`)
let s = (self) # TODO avoid copy
if not s.o: s.e
else: def
else:
when T isnot void:
template value: T {.used, inject.} = s.v
def
func flatten*[T, E](self: Result[Result[T, E], E]): Result[T, E] =
## Remove one level of nesting

View File

@ -69,11 +69,13 @@ block:
doAssert rOk.get() == rOk.unsafeGet()
doAssert rOk.valueOr(failFast()) == rOk.value()
let rErrV = rErr.valueOr: 100
doAssert rErrV == 100
let rErrV = rErr.valueOr:
error.len
doAssert rErrV == rErr.error.len()
let rOkV = rOk.errorOr: "quack"
doAssert rOkV == "quack"
let rOkV = rOk.errorOr:
$value
doAssert rOkV == $rOk.get()
# Exceptions -> results
func raises(): int =