Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 18 additions & 12 deletions doc/manual.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2981,11 +2981,13 @@ Example:

.. code-block:: nim

case readline(stdin)
let line = readline(stdin)
case line
of "delete-everything", "restart-computer":
echo "permission denied"
of "go-for-a-walk": echo "please yourself"
else: echo "unknown command"
elif line.len == 0: echo "empty" # optional, must come after `of` branches
else: echo "unknown command" # ditto

# indentation of the branches is also allowed; and so is an optional colon
# after the selecting expression:
Expand All @@ -2996,19 +2998,23 @@ Example:
else: echo "unknown command"


The `case` statement is similar to the if statement, but it represents
The `case` statement is similar to the `if` statement, but it represents
a multi-branch selection. The expression after the keyword `case` is
evaluated and if its value is in a *slicelist* the corresponding statements
(after the `of` keyword) are executed. If the value is not in any
given *slicelist* the `else` part is executed. If there is no `else`
part and not all possible values that `expr` can hold occur in a
*slicelist*, a static error occurs. This holds only for expressions of
ordinal types. "All possible values" of `expr` are determined by `expr`'s
type. To suppress the static error an `else` part with an
empty `discard` statement should be used.
given *slicelist*, trailing `elif` and `else` parts are executed using same
semantics as for `if` statement, and `elif` is handled just like `else: if`.
If there are no `else` or `elif` parts and not
all possible values that `expr` can hold occur in a *slicelist*, a static error occurs.
This holds only for expressions of ordinal types.
"All possible values" of `expr` are determined by `expr`'s type.
To suppress the static error an `else: discard` should be used.

For non-ordinal types, it is not possible to list every possible value and so
these always require an `else` part.
An exception to this rule is for the `string` type, which currently doesn't
require a trailing `else` or `elif` branch; it's unspecified whether this will
keep working in future versions.

Because case statements are checked for exhaustiveness during semantic analysis,
the value in every `of` branch must be a constant expression.
Expand Down Expand Up @@ -3054,15 +3060,15 @@ won't work:
var foo = Foo(x: @[])
foo.get_x().add("asd")

This can be fixed by explicitly using `return`:
This can be fixed by explicitly using `result` or `return`:

.. code-block:: nim
proc get_x(x: Foo): var seq[string] =
case true
of true:
return x.x
result = x.x
else:
return x.x
result = x.x


When statement
Expand Down