Last active
April 23, 2020 15:55
-
-
Save planetis-m/d1571d25917e670e9882e48618d6a834 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## This template provides syntactic sugar and | |
## that emulates/substitutes an optional type | |
type | |
SomePointer = ref | ptr | pointer | proc | |
template `?=`*(value, call: untyped): bool = | |
## Operator that unwraps the "optional" value that `call` returns, into `value`. | |
## This can be `(bool, T)` or any pointer type. | |
## Used only as an if condition | |
when call is SomePointer: | |
(let value = call; system.`!=`(value, nil)) | |
else: | |
(let (isSome, value) = call; isSome) | |
when isMainModule: | |
# proc that returns (bool, T) | |
proc test1(): (bool, int) = | |
if true: (true, 2) # some value | |
else: (false, 0) # none | |
if a ?= test1(): | |
echo "value: ", a | |
type | |
Foo = ref object | |
value: int | |
# proc that returns ref | |
proc test2(): Foo = discard | |
if a ?= test2(): | |
echo "fail" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment