Functions that take any number of values

fmt.Println takes any number of values, even none at all. You can write functions like that too. A variadic function accepts any number of values for its last parameter. To make one, write three dots ... before the parameter's type:

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))
	fmt.Println(sum(10, 20))
	fmt.Println(sum())
}

Output:

6
30
0

nums ...int means "any number of int values". The caller lists them with commas, as in sum(1, 2, 3), or gives none, as in sum().

The values arrive as a slice

Inside the function, nums is a normal slice of type []int. That is why the range loop above works on it. This program prints the slice that the function receives:

package main

import "fmt"

func show(nums ...int) {
	fmt.Println(nums, len(nums))
}

func main() {
	show(4, 5, 6)
	show()
}

Output:

[4 5 6] 3
[] 0

With no values, nums is an empty slice, and a loop over it runs zero times. That is why sum() returned 0 and not an error.

Passing a slice you already have

Say the numbers are already in a slice. You cannot pass the slice as it is. The function wants separate int values, and a slice is one value of a different type:

package main

import "fmt"

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

func main() {
	values := []int{10, 20, 30}
	fmt.Println(sum(values))
}

Output:

# command-line-arguments
./main.go:15:18: cannot use values (variable of type []int) as int value in argument to sum

Put three dots after the slice, as in sum(values...). This spreads the slice: Go passes its elements as the values. Here is the same program with only line 15 changed:

package main

import "fmt"

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

func main() {
	values := []int{10, 20, 30}
	fmt.Println(sum(values...))
}

Output:

60

So the dots go before the type when you declare the parameter (nums ...int), and after the slice when you spread it (values...). You cannot mix the two forms in one call. sum(5, values...) does not compile, and Go reports "too many arguments in call to sum".

Other parameters come first

Only the last parameter can be variadic. Normal parameters go before it:

package main

import "fmt"

func printTotal(label string, nums ...int) {
	total := 0
	for _, n := range nums {
		total += n
	}
	fmt.Println(label, total)
}

func main() {
	printTotal("Monday:", 5, 7, 3)
	printTotal("Tuesday:")
}

Output:

Monday: 15
Tuesday: 0

The first value always goes to label, and all the values after it go into nums.

In the exercise, finish the variadic function sumOrders and pass it the whole slice of order totals by spreading it.