mirror of
https://github.com/status-im/nim-stew.git
synced 2025-01-23 10:29:44 +00:00
result: expose value/error in errorOr/valueOr
* fix error type as well
This commit is contained in:
parent
d2ae2889e8
commit
6ad35b876f
@ -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
|
||||
|
@ -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 =
|
||||
|
Loading…
x
Reference in New Issue
Block a user