Go variadic function

A variadic function can accept a variable number of parameters. For instance, when we want to calculate the sum of values, we might have four, five, six, etc. values to pass to the function.

We use the ... (ellipses) operator to define a variadic function.

Go variadic function

In the example, we have a sum function that accepts a variable number of parameters.


package main

import "fmt"

func main() {

    s1 := sum(1, 2, 3)
    s2 := sum(1, 2, 3, 4)
    s3 := sum(1, 2, 3, 4, 5)

    fmt.Println(s1, s2, s3)
}

func sum(nums ...int) int {

    res := 0

    for _, n := range nums {
        res += n
    }

    return res
}

Output:

6 10 15

The nums variable is a slice, which contains all values passed to the sum function. We loop over the slice and calculate the sum of the parameters:


func sum(nums ...int) int {

    res := 0

    for _, n := range nums {
        res += n
    }

    return res
}

Comments