What is a Variadic Function in Golang

A variadic function in Go accepts a variable number of arguments. You can define a variadic function by using the syntax before the type of the last parameter. This suggests that the function can accept any number of arguments of that type, which will be accessible within the function as a slice.


package main

import (

func Sum(nums ...int) int {
  total := 0
  for _, num := range nums {
    total += num
  return total

func main() {
  fmt.Println(Sum(1, 2))
  fmt.Println(Sum(1, 2, 3, 4, 5, 6))

  numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}



In this code example, we defined a Sum() variadic function that accepts any number of integers.

The nums parameter is a slice that contains all the integer arguments passed to the function. Inside the function, we iterated through the nums slice and calculated the sum of the integers.

Inside the main() function, we demonstrated different ways to call the Sum() variadic function with no arguments, two arguments, multiple arguments, and by passing a slice of integers using the … syntax.

A variadic function provides flexibility in handling a variable number of arguments and is commonly used for functions like fmt.Printf() can format various values based on the format string.

That’s it.

Leave a Comment