Variadic Functions And Slice Expansion

Declare variadic functions, forward their arguments with the ... spread to inner calls, and hand whole slices to them without copying.

GoCli Tooling

Code

gosnippet
27 lines
package main

import "fmt"

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

// 包装函数转发可变参数:必须展开再传,否则会变成一个 []int 参数
func report(label string, nums ...int) {
	fmt.Printf("%s: sum=%d from %d values\n", label, sum(nums...), len(nums))
}

func main() {
	fmt.Println("empty:", sum())
	fmt.Println("direct:", sum(1, 2, 3))

	values := []int{4, 5, 6}
	fmt.Println("spread:", sum(values...))

	report("batch", values...)
	report("empty")
}

Variadic declaration

sum(nums …int) accepts any number of int arguments; inside the function nums is an ordinary []int slice, summed by a range loop. sum() with no arguments is legal and returns 0.

Forwarding with …

A wrapper like report(label string, nums …int) must expand again when calling inner variadic functions: sum(nums…) forwards the elements. Writing sum(nums) instead would compile as a single []int argument to a non-existent overload and fail to type-check against sum’s int-variadic signature.

Call shapes

The demo shows four forms: direct arguments (sum(1, 2, 3)), an empty call (sum()), slice expansion (sum(values…)), and a wrapper that forwards (report(“batch”, values…)) plus report(“empty”) which forwards an empty variadic.

Interactive Tools for This Topic

FAQ

Why does sum(nums) fail inside a variadic wrapper?
sum expects zero or more ints, not a []int argument; the spread form sum(nums...) is required to forward the elements one by one.
Is a zero-argument variadic call valid?
Yes. sum() and report("empty") both exercise the empty case; the range loop simply sees no elements.