Variadic Functions

2-minute read

These are functions that can accept any number of arguments. We have already seen Println from the fmt package. It can accept many values and string them together to be outputted into the console. Here is a function that accepts any number of integers and returns their product:

package main

import "fmt"

func Product(numbers ...int) int {
	product := 1

	for _, number := range numbers {
		product *= number
	}
	return product
}

func main() {
	a := Product(4, 5, 2)
	b := Product(-1, 2, 5)
	fmt.Println("a:", a)
	fmt.Println("b:", b)
}
variadic-product.go
Copy

Defining the function this way allows us to access the values in the numbers variable as if they were in a slice. In fact, we can pass a slice of integers into the function in the following manner and it will still work:

package main

import "fmt"

func Product(numbers ...int) int {
	product := 1

	for _, number := range numbers {
		product *= number
	}
	return product
}

func main() {
	set := []int{4, 5, 2}
	a := Product(set...)
	fmt.Println("a:", a)
}
variadic-product-slice.go
Copy

We can have a function that accepts a bunch of strings and returns the concatenation of these strings:

package main

import "fmt"

func Concat(strings ...string) string {
	cat := ""
	for _, str := range strings {
		cat += str
	}
	return cat
}

func main() {
	fmt.Println("result:", Concat())
	fmt.Println("result:", Concat("hello", "there"))
	fmt.Println("result:", Concat("how", "are", "you"))
}
variadic-concat.go
Copy

Support us via BuyMeACoffee