use runnableExamples in options (#16503)
This commit is contained in:
parent
b8658a3e24
commit
805917768d
1 changed files with 17 additions and 26 deletions
|
|
@ -23,38 +23,29 @@
|
||||||
## Let's start with an example: a procedure that finds the index of a character
|
## Let's start with an example: a procedure that finds the index of a character
|
||||||
## in a string.
|
## in a string.
|
||||||
##
|
##
|
||||||
## .. code-block:: nim
|
runnableExamples:
|
||||||
##
|
proc find(haystack: string, needle: char): Option[int] =
|
||||||
## import options
|
for i, c in haystack:
|
||||||
##
|
if c == needle:
|
||||||
## proc find(haystack: string, needle: char): Option[int] =
|
return some(i)
|
||||||
## for i, c in haystack:
|
return none(int) # This line is actually optional,
|
||||||
## if c == needle:
|
# because the default is empty
|
||||||
## return some(i)
|
|
||||||
## return none(int) # This line is actually optional,
|
let found = "abc".find('c')
|
||||||
## # because the default is empty
|
assert found.isSome and found.get() == 2
|
||||||
##
|
|
||||||
## .. code-block:: nim
|
|
||||||
##
|
|
||||||
## let found = "abc".find('c')
|
|
||||||
## assert found.isSome and found.get() == 2
|
|
||||||
##
|
|
||||||
## The `get` operation demonstrated above returns the underlying value, or
|
## The `get` operation demonstrated above returns the underlying value, or
|
||||||
## raises `UnpackDefect` if there is no value. Note that `UnpackDefect`
|
## raises `UnpackDefect` if there is no value. Note that `UnpackDefect`
|
||||||
## inherits from `system.Defect`, and should therefore never be caught.
|
## inherits from `system.Defect`, and should therefore never be caught.
|
||||||
## Instead, rely on checking if the option contains a value with
|
## Instead, rely on checking if the option contains a value with
|
||||||
## `isSome <#isSome,Option[T]>`_ and `isNone <#isNone,Option[T]>`_ procs.
|
## `isSome <#isSome,Option[T]>`_ and `isNone <#isNone,Option[T]>`_ procs.
|
||||||
##
|
##
|
||||||
## How to deal with an absence of a value:
|
## How to deal with an absence of a value:
|
||||||
##
|
|
||||||
## .. code-block:: nim
|
runnableExamples:
|
||||||
##
|
let result = none(int)
|
||||||
## let result = "team".find('i')
|
# It has no value:
|
||||||
##
|
assert(result.isNone)
|
||||||
## # Nothing was found, so the result is `none`.
|
|
||||||
## assert(result == none(int))
|
|
||||||
## # It has no value:
|
|
||||||
## assert(result.isNone)
|
|
||||||
|
|
||||||
import typetraits
|
import typetraits
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue