fix: use a temp var in withValue (#1010)

This commit is contained in:
diegomrsantos 2024-01-18 16:25:56 +01:00 committed by GitHub
parent e3c967ad19
commit 2725be64ba
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 21 additions and 2 deletions

View File

@ -89,8 +89,27 @@ template exceptionToAssert*(body: untyped): untyped =
res
template withValue*[T](self: Opt[T] | Option[T], value, body: untyped): untyped =
if self.isSome:
let value {.inject.} = self.get()
## This template provides a convenient way to work with `Option` types in Nim.
## It allows you to execute a block of code (`body`) only when the `Option` is not empty.
##
## `self` is the `Option` instance being checked.
## `value` is the variable name to be used within the `body` for the unwrapped value.
## `body` is a block of code that is executed only if `self` contains a value.
##
## The `value` within `body` is automatically unwrapped from the `Option`, making it
## simpler to work with without needing explicit checks or unwrapping.
##
## Example:
## ```nim
## let myOpt = Opt.some(5)
## myOpt.withValue(value):
## echo value # Will print 5
## ```
##
## Note: This is a template, and it will be inlined at the call site, offering good performance.
let temp = (self)
if temp.isSome:
let value {.inject.} = temp.get()
body
macro withValue*[T](self: Opt[T] | Option[T], value, body, body2: untyped): untyped =