use runnableExamples in options (#16503)

This commit is contained in:
flywind 2020-12-30 09:26:49 -06:00 • committed by GitHub
commit 805917768d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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