Documented how to work with =? in generic procs

This commit is contained in:
Mark Spanbroek 2021-04-12 18:05:01 +02:00
parent a8fe7bf7b3
commit a2023ae18e
2 changed files with 22 additions and 0 deletions

View File

@ -63,6 +63,17 @@ else:
# this is reached, and y is not defined
```
When using `=?` in generic code you may face errors about undeclared
identifiers. This is a limitation of Nim and can be worked around with a `mixin`
statement:
```nim
proc genericProc[T](option: ?T) =
if value =? option:
mixin value
# use value
```
### Option chaining
To safely access fields and call procs, you can use the `.?` operator:

View File

@ -105,6 +105,17 @@ suite "optionals":
let b {.used.} = a
check count == 1
test "=? works in generic code with mixin statement":
proc toString[T](option: ?T): string =
if value =? option:
mixin value
$value
else:
"none"
check 42.some.toString == "42"
check int.none.toString == "none"
test ".?[] can be used for indexing tables without raising KeyError":
let table = @{"a": 1, "b": 2}.toTable
check table.?["a"] == 1.some