Discard statement

Example:

  1. proc p(x, y: int): int =
  2. result = x + y
  3. discard p(3, 4) # discard the return value of `p`

The discard statement evaluates its expression for side-effects and throws the expression’s resulting value away, and should only be used when ignoring this value is known not to cause problems.

Ignoring the return value of a procedure without using a discard statement is a static error.

The return value can be ignored implicitly if the called proc/iterator has been declared with the discardable pragma:

  1. proc p(x, y: int): int {.discardable.} =
  2. result = x + y
  3. p(3, 4) # now valid

however the discardable pragma does not work on templates as templates substitute the AST in place. For example:

  1. {.push discardable .}
  2. template example(): string = "https://nim-lang.org"
  3. {.pop.}
  4. example()

This template will resolve into “https://nim-lang.org“ which is a string literal and since {.discardable.} doesn’t apply to literals, the compiler will error.

An empty discard statement is often used as a null statement:

  1. proc classify(s: string) =
  2. case s[0]
  3. of SymChars, '_': echo "an identifier"
  4. of '0'..'9': echo "a number"
  5. else: discard