100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Go

Variadic Functions in Go

Learn how to write and call functions that accept a variable number of arguments.

FunctionsIntermediate6 min readJul 8, 2026
Analogies

Introduction

A variadic function accepts a variable number of arguments of the same type. Go marks the final parameter with an ellipsis (...) before its type, allowing callers to pass zero, one, or many values without needing overloaded function signatures. fmt.Println is a familiar example of a variadic function.

🏏

Cricket analogy: A commentator can call out zero, one, or many boundaries in a single sentence, 'Four! Four! Six!', just as a variadic function accepts any number of same-type arguments marked with an ellipsis, without needing separate commentary formats.

Syntax

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

Explanation

Inside the function, the variadic parameter (nums in this case) behaves like a slice of the given type ([]int here), so it can be ranged over or indexed normally. Callers can pass individual arguments separated by commas, e.g. sum(1, 2, 3), or spread an existing slice using the same ellipsis syntax, e.g. sum(mySlice...). A function can have only one variadic parameter, and it must be the last parameter in the list.

🏏

Cricket analogy: Inside the innings, the tally of runs (nums) behaves like a normal list you can iterate over ball by ball, and a captain can call out scores individually, sum(4, 6, 1), or hand over an entire pre-recorded over as one spread, sum(over...).

Example

go
package main

import "fmt"

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

func main() {
    fmt.Println(sum(1, 2, 3))

    values := []int{4, 5, 6, 7}
    fmt.Println(sum(values...))

    fmt.Println(sum())
}

// Output:
// 6
// 22
// 0

Key Takeaways

  • Variadic parameters are declared with ...type as the last parameter.
  • Inside the function, the variadic parameter behaves like a regular slice.
  • Callers can pass individual values or spread an existing slice using slice....
  • Calling a variadic function with zero arguments is valid and yields an empty slice.
  • Only one variadic parameter is allowed per function, and it must come last.

Practice what you learned

Was this page helpful?

Topics covered

#Go#GoProgrammingStudyNotes#Programming#VariadicFunctionsInGo#Variadic#Functions#Syntax#Explanation#StudyNotes#SkillVeris