Go: Pass a slice to a variadic function

You can pass a slice s directly to a variadic funtion using the s... notation.

func main() {
	primes := []int{2, 3, 5, 7}
	fmt.Println(Sum(primes...)) // 17
}	

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

The ... syntax can’t be applied directly to an array. You must use an intermediate slice:

fmt.Println(Sum(myArray[:]...))

Comments