Skip to content

Instantly share code, notes, and snippets.

@planetis-m
Last active April 23, 2020 15:55
Show Gist options
  • Save planetis-m/d1571d25917e670e9882e48618d6a834 to your computer and use it in GitHub Desktop.
Save planetis-m/d1571d25917e670e9882e48618d6a834 to your computer and use it in GitHub Desktop.
## 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