0Pricing
Go Academy · Lesson

Variadic Functions

Accepting a variable number of arguments

What Is a Variadic Function?

A variadic function accepts zero or more arguments of a specified type, collected into a slice:

func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

fmt.Println(sum(1, 2, 3, 4)) // 10

The ...T Syntax

Use ...T as the last parameter type. Inside the function, it is a []T:

  • Can be called with 0 or more arguments
  • The variadic parameter must be the last one
  • Only one variadic parameter per function

All lessons in this course

  1. Function Basics and Signatures
  2. Multiple Return Values
  3. Variadic Functions
  4. defer, Anonymous Functions & Closures
← Back to Go Academy