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)
}
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)
}
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"))
}
The last parameter
It is important to note that the parameter that represents the slice containing the numerous values passed into the function must be last in the function definition. The following is not valid:
func myFunction(messages ...string, recipient string){
// do something
}
func main(){
myFunction("Hello", "How are you?", "John")
}
In such a case, there is no way for the program to know that John is the recipient. The messages variable must be last to let the compiler know that any number of messages can follow the recipient value:
func myFunction(recipient string, messages ...string){
// do something
}
func main(){
myFunction("John", "Hello", "How are you?")
}