Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add get(Option[T], var T): bool procedure #23261

Open
wants to merge 14 commits into
base: devel
Choose a base branch
from
28 changes: 28 additions & 0 deletions lib/pure/options.nim
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,34 @@ proc get*[T](self: Option[T], otherwise: T): T {.inline.} =
else:
otherwise

proc unpack*[T](self: Option[T], val: out T): bool {.inline.} =
## Unpacks the contents of the `Option` if there are any, and returns true.
## Otherwise, it simply returns false and sets the value to its default one.
runnableExamples:
var storage: int

if some(1337).unpack(storage):
assert storage == 1337

if not self.isSome:
val = default(T)
false
else:
val = self.get()
true

template `?=`*[T](x: untyped{ident}, self: Option[T]): bool =
## Unpacks the contents of the `Option` into a value name provided if there are any, and returns true.
## Otherwise, returns false and no value is created.
runnableExamples:
let container = some(1337)
var store: int
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
var store: int

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you force-push this one? I'm not on my computer now.


if store ?= container:
assert x == 1337

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
var x: T

unpack(self, x)

proc get*[T](self: var Option[T]): var T {.inline.} =
## Returns the content of the `var Option` mutably. If it has no value,
## an `UnpackDefect` exception is raised.
Expand Down
13 changes: 13 additions & 0 deletions tests/stdlib/toptions.nim
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,19 @@ proc main() =
let x = none(cstring)
doAssert x.isNone
doAssert $x == "none(cstring)"

# Store option's value in a variable, and return a bool
block:
let
x = some(1984)
y = none(int)

var a, b: int

doAssert x.unpack(a)
doAssert a == 1984

doAssert not y.unpack(b)

static: main()
main()
Expand Down
Loading