Does Golang support variadic function?

While using the variadic parameters, you need to use loop in the datatype inside your function.

func Add(nums... int) int {
    total := 0
    for _, v := range nums {
        total += v
    }
    return total  
}

func main() {
    fmt.Println("Hello, playground")
    fmt.Println(Add(1, 3, 4, 5,))
}

You've pretty much got it, from what I can tell, but the syntax is ...int. See the spec:

Given the function and call

func Greeting(prefix string, who ...string)
Greeting("hello:", "Joe", "Anna", "Eileen")

within Greeting, who will have the value []string{"Joe", "Anna", "Eileen"}


Golang have a very simple variadic function declaration

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 int's as arguments.

package main

import (
    "fmt"
)

func sum(nums ...int) {
    fmt.Println(nums)
    for _, num := range nums {
        fmt.Print(num)
    }
}

func main() {
    sum(1, 2, 3, 4, 5, 6)
}

Output of the above program:

[1 2 3 4 5 6]

1 2 3 4 5 6

Tags:

Go