Avoid wrapping option in option when using .?[] operator

This commit is contained in:
Mark Spanbroek 2021-05-04 16:17:09 +02:00
parent e8ab268758
commit 8bf4f27f30
2 changed files with 14 additions and 0 deletions

View File

@ -62,6 +62,15 @@ template `|?`*[T](option: ?T, fallback: T): T =
else:
fallback
macro `.?`*[T](option: ?T, brackets: untyped{nkBracket}): untyped =
let index = brackets[0]
quote do:
type U = typeof(`option`.unsafeGet().?[`index`].unsafeGet())
if `option`.isSome:
`option`.unsafeGet().?[`index`]
else:
U.none
Option.liftUnary(`-`)
Option.liftUnary(`+`)
Option.liftUnary(`@`)

View File

@ -230,6 +230,11 @@ suite "optionals":
check (a & b) == 42.some
test ".?[] avoids wrapping option in option":
let a = @[41, 42].some
check a.?[1] == 42.some
test "examples from readme work":
var x: ?int