Multiple Return Values in Nim
Nim has built-in support for multiple return values. This feature is often used in idiomatic Nim, for example to return both result and error values from a function.
The (int, int)
in this function signature shows that the function returns 2 int
s.
proc vals(): (int, int) =
return (3, 7)
Here’s how we use this function:
import strformat
proc main() =
# Here we use the 2 different return values from the
# call with multiple assignment.
let (a, b) = vals()
echo a
echo b
# If you only want a subset of the returned values,
# use the discard statement.
let (_, c) = vals()
echo c
main()
When you run this program, you’ll see:
$ nim c -r multiple_return_values.nim
3
7
7
In Nim, we use parentheses ()
to group multiple return values, and we can use tuple unpacking to assign these values to variables. If we want to ignore a return value, we can use the underscore _
as a placeholder, similar to the blank identifier in other languages.
The discard
statement in Nim is used when we want to explicitly ignore the result of a function call. In this case, we’re using tuple unpacking, so we don’t need to use discard
.
Accepting a variable number of arguments is another nice feature of Nim procedures; we’ll look at this next.