Variadic Functions in Nim

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

Here’s a function that will take an arbitrary number of ints as arguments:

proc sum(nums: varargs[int]) =
    echo nums, " "
    var total = 0
    for num in nums:
        total += num
    echo total

proc main() =
    # Variadic functions can be called in the usual way with individual arguments.
    sum(1, 2)
    sum(1, 2, 3)

    # If you already have multiple args in a slice, apply them to a variadic function using `func(slice[])` like this.
    let nums = [1, 2, 3, 4]
    sum(nums[])

main()

To run the program, save the code to a file with a .nim extension (e.g., variadic_functions.nim) and use Nim’s command-line tools to execute it.

$ nim compile --run variadic_functions.nim
[1, 2] 
3
[1, 2, 3] 
6
[1, 2, 3, 4] 
10

Another key aspect of functions in Nim is their ability to form closures, which we’ll look at next.

Next example: Closures.