ProgramGuru

Variadic Functions

Start with Variadic Functions

A variadic function accepts a variable number of arguments of the same element type. It is useful for totals, aggregation and flexible APIs.

What you’ll learn

  • Explain the main purpose of variadic functions.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Declare the final parameter as values ...int. Inside the function it behaves like a []int slice. The caller may pass individual numbers or expand an existing slice with numbers....

A variadic parameter must be the last parameter. Calling it with no variadic arguments is valid; the function then sees an empty slice. Standard-library functions such as fmt.Println also accept variadic arguments.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for variadicArguments are collected into a slice-like parameter.sum(4,6)Step 1values = [4,6]Step 2Loop over valuesStep 3Return 10Step 4Arguments are collected into a slice-like parameter.
Arguments are collected into a slice-like parameter.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func sum(values ...int) int {
	total := 0
	for _, value := range values {
		total += value
	}
	return total
}
func main() {
	fmt.Println("Two:", sum(4, 6))
	numbers := []int{1, 2, 3, 4}
	fmt.Println("Slice:", sum(numbers...))
	fmt.Println("Empty:", sum())
}

Output

Two: 10
Slice: 10
Empty: 0

Trace what the program does

The first call collects 4 and 6 and returns 10. Expanding numbers... passes its four elements as variadic values and returns 10 again. With no values the total stays zero.

Avoid common mistakes

  • A variadic parameter must appear at the end of the parameter list.
  • Passing a slice as individual variadic arguments requires ... at the call site.

Try it yourself

Write a variadic maximum(values ...int) for nonempty inputs, and decide how to handle the empty case.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What is the type of values inside func sum(values ...int)?
Choose one answer. You can try again.

Answer and explanation

[]int

Correct. The first call collects 4 and 6 and returns 10.

What you should remember

You have practiced Variadic Functions in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Anonymous Functions →