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:


sum(1,1)
sum(2,3,4)
sum(1,2,3,4,5,6,7)

Then in the sum function, add each number to the total amount with a for loop.


package main

import "fmt"

func sum(numbers ...int) {
    total := 0
    for _, num := range numbers {
        total += num
    }
    fmt.Println(total)
}

func main() {
    sum(2,3,4)
}

$ go run example.go
9

Exercises

  • Create a variadic function that prints the names of students