mirror of
https://github.com/logos-storage/questionable.git
synced 2026-01-03 22:33:07 +00:00
Documented how to work with =? in generic procs
This commit is contained in:
parent
a8fe7bf7b3
commit
a2023ae18e
11
Readme.md
11
Readme.md
@ -63,6 +63,17 @@ else:
|
|||||||
# this is reached, and y is not defined
|
# 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
|
### Option chaining
|
||||||
|
|
||||||
To safely access fields and call procs, you can use the `.?` operator:
|
To safely access fields and call procs, you can use the `.?` operator:
|
||||||
|
|||||||
@ -105,6 +105,17 @@ suite "optionals":
|
|||||||
let b {.used.} = a
|
let b {.used.} = a
|
||||||
check count == 1
|
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":
|
test ".?[] can be used for indexing tables without raising KeyError":
|
||||||
let table = @{"a": 1, "b": 2}.toTable
|
let table = @{"a": 1, "b": 2}.toTable
|
||||||
check table.?["a"] == 1.some
|
check table.?["a"] == 1.some
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user