Variadic functions can be called with any number of arguments.
You’ve already used one variadic function:
fmt.Print(..)
. That function can be called with many
arguments, like this:
fmt.Print("hello"," ","world","!","\n").
A function is said to be variadic, if the number of arguments are not explictly defined.
Example
Variadic function
Define a variadic functions in this way:
func sum(numbers ...int) {
In this case it will take any amount of numbers (integers).
You can call a variadic function as you call normal functions. Any of the bottom calls will work:
(1,1)
sum(2,3,4)
sum(1,2,3,4,5,6,7) sum
Then in the sum function, add each number to the total amount with a for loop.
package main
import "fmt"
func sum(numbers ...int) {
:= 0
total for _, num := range numbers {
+= num
total }
.Println(total)
fmt}
func main() {
(2,3,4)
sum}
$ go run example.go
9
Exercises
- Create a variadic function that prints the names of students