Skip to content
Codewilds

Lesson 12 of 38 · Functions

Go Variadic Functions: ...T Parameters

medium20 XP3 min read

fmt.Println happily takes one argument, five, or none at all. Your own functions can do the same: a variadic function accepts any number of arguments of one type.

Variadic functions are the natural shape for helpers like sums, joins and logging, where the caller simply lists the values: Sum(3, 4, 5) reads better than building a list first.

The ...T parameter

package main

import "fmt"

// greetAll prints a greeting for every name it receives.
func greetAll(greeting string, names ...string) {
	fmt.Println(len(names), "names")
	for _, name := range names {
		fmt.Println(greeting + ", " + name + "!")
	}
}

func main() {
	greetAll("Hi", "Ann", "Bo")
	greetAll("Hello")
}
2 names
Hi, Ann!
Hi, Bo!
0 names

Writing ... before the type of the last parameter makes it variadic. Inside the function, names has the type []string — a slice, Go's ordered list of values, which the next chapter covers in depth. For now you need three things: len(names) is the number of elements, names[0] is the first one, and for _, name := range names visits every element in order (range also yields the index, which _ discards).

Calling with no variadic arguments is allowed: the slice is then empty, len(names) is 0 and the loop simply doesn't run. Ordinary parameters like greeting are still required.

Spreading a slice with xs...

When the values already sit in a slice, put ... after it in the call. Its elements become the variadic arguments:

guests := []string{"Cy", "Dee"}
greetAll("Welcome", guests...) // same as greetAll("Welcome", "Cy", "Dee")

You can now read the signature of the function you've used since your first program:

func Println(a ...any) (n int, err error)

any means "a value of any type", which is why a single call can mix strings and numbers. And yes — Println returns two values (the number of bytes written and an error) that programs almost always ignore.

Variadic or slice parameter?

Choose ...T when callers usually list values by hand: Sum(1, 2, 3), JoinWords(" ", first, last). Choose a plain slice parameter, like func Average(scores []float64), when the data is naturally a collection that already lives in a slice — scores loaded from a file, for example. Callers then don't need ..., and the signature clearly says "give me a list".

If a function needs at least one value, say so in the signature: with func MaxOf(first int, rest ...int) int, calling MaxOf() is a compile error instead of a crash at run time.

Common mistakes

  • Forgetting ... when passing a slice: Sum(nums) doesn't compile — a []int is not an int.
  • Mixing listed and spread arguments: Sum(1, nums...) doesn't compile either. List every value, or spread a single slice.
  • A variadic parameter that isn't last: only the final parameter may use ....
  • Assuming there is an argument: nums[0] panics with index out of range [0] with length 0 when the caller passed nothing.
  • Changing the elements: with xs... the function receives the caller's slice itself, not a copy, so assigning to nums[i] changes the caller's data too.

Assignment

Write four variadic functions:

  1. Sum(nums ...int) int returns the sum of all numbers. Sum() is 0.
  2. Average(nums ...int) float64 returns the average, keeping the decimal part. With no numbers it returns 0. Reuse Sum by passing the numbers on: Sum(nums...).
  3. JoinWords(sep string, words ...string) string joins the words with sep between them. Empty words are skipped, so a missing middle name doesn't leave a double space. With no non-empty words it returns "".
  4. MaxOf(first int, rest ...int) int returns the largest of all its arguments. Write the comparison yourself rather than calling Go's built-in max.
Sum(1, 2, 3, 4)                       // 10
Average(1, 2, 3, 4)                   // 2.5
JoinWords("-", "a", "b", "c")         // "a-b-c"
JoinWords(" ", "Ada", "", "Lovelace") // "Ada Lovelace"
MaxOf(3, 9, 2)                        // 9
MaxOf(7)                              // 7

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Function parameters in other languages

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+20 XP

Lesson 12 is part of the full course. The first 9 lessons are free.

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.