Does Golang support variadic function?

Go

Go Problem Overview


I wonder if there a way where I can define a function for unknown number of variables in Go.

Something like this

func Add(num1... int) int {
 	return args
}

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

I want to generalize the function Add for any number of inputs.

Go Solutions


Solution 1 - Go

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

Solution 2 - Go

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

Solution 3 - Go

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2671513View Question on Stackoverflow
Solution 1 - GoAlexander BauerView Answer on Stackoverflow
Solution 2 - Gogopher63View Answer on Stackoverflow
Solution 3 - GoASHWIN RAJEEVView Answer on Stackoverflow