result: add `Opt.some` / `Opt.none` (#117)

This commit is contained in:
Jacek Sieka 2022-06-17 12:45:22 +02:00 committed by GitHub
parent 981551ae5d
commit dad28a269f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 1 deletions

View File

@ -884,6 +884,24 @@ func filter*[T](
# Options compatibility
template some*[T](O: type Opt, v: T): Opt[T] =
## Create an `Opt` set to a value
##
## ```
## let o = Opt.some(42)
## assert o.isSome and o.get() == 42
## ```
Opt[T].ok(v)
template none*(O: type Opt, T: type): Opt[T] =
## Create an `Opt` set to none
##
## ```
## let o = Opt.none(int)
## assert o.isNone
## ```
Opt[T].err()
template isSome*(o: Opt): bool =
## Alias for `isOk`
isOk o

View File

@ -351,6 +351,9 @@ block: # Result[T, void] aka `Opt`
doAssert oOk.filter(proc(x: int): bool = false).isErr()
doAssert oErr.filter(proc(x: int): bool = true) == oErr
doAssert Opt.some(42).get() == 42
doAssert Opt.none(int).isNone()
block: # `cstring` dangling reference protection
type CSRes = Result[void, cstring]
@ -398,4 +401,3 @@ block: # Experiments
counter2 += 1
doAssert counter2 == 1, "one-item collection when set"