Back to Blog

Variadic Functions (Variable Arguments & Spread Operator) - Go Tutorial for Beginners #12

Sandy LaneSandy Lane

Video: Variadic Functions (Variable Arguments & Spread Operator) - Go Tutorial for Beginners #12 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Variadic Functions (Variable Arguments & Spread Operator) in Go

Variadic functions in Go allow you to write functions that accept any number of arguments of a specified type. This is useful for flexible APIs like summing numbers or logging messages. Inside the function, the variadic parameter is treated as a slice, enabling iteration and manipulation.

Code

package main

import (
  "fmt"
)

// Variadic function - accepts any number of ints
func sum(nums ...int) int {
  total := 0
  // nums is a slice of int inside the function
  for _, n := range nums {
    total += n
  }
  return total
}

func main() {
  // Call with any number of arguments
  fmt.Println("Sum:", sum(1, 2, 3, 4, 5))

  // Spread a slice into a variadic function using ...
  numbers := []int{10, 20, 30}
  fmt.Println("Sum with slice:", sum(numbers...))

  // Mixed parameters: regular + variadic
  greetAll("Hello", "Alice", "Bob", "Charlie")
}

// Mixed parameters example: greeting + any number of names
func greetAll(greeting string, names ...string) {
  for _, name := range names {
    fmt.Println(greeting, name)
  }
}

Key Points

  • Variadic parameters use the syntax func f(args ...Type) and behave like slices inside the function.
  • You can call variadic functions with zero or more arguments, or pass a slice using the spread operator slice....
  • Functions can combine regular parameters with variadic ones, but the variadic parameter must be last.
  • Common Go functions like fmt.Println use variadic parameters to accept any number of arguments.
  • The spread operator is useful for forwarding slices to variadic functions, enabling flexible code reuse.