Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Golang support variadic function?

Tags:

go

People also ask

What is variadic function in Golang?

A variadic function is a function that accepts a variable number of arguments. In Golang, it is possible to pass a varying number of arguments of the same type as referenced in the function signature.

How do you write a function in Golang?

In Golang, we declare a function using the func keyword. A function has a name, a list of comma-separated input parameters along with their types, the result type(s), and a body. The input parameters and return type(s) are optional for a function. A function can be declared without any input and output.

Is printf variadic function?

Variadic functions are functions (e.g. printf) which take a variable number of arguments.


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"}


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,))
}

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