Ellipsis (…)#
The ellipsis (...) in Go is used for variadic functions and unpacking slices.
Variadic Functions#
A variadic function can accept zero or more arguments of a specific type. Inside the function, the variadic parameter is treated as a slice.
eg.
func mySum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println(mySum(1, 2, 3)) // 6
}Unpacking#
The ellipsis is used to “unpack” or “expand” a slice into individual arguments when calling a variadic function.
Note that the signature of append is func append(slice []T, elems ...T) []T.
eg.
func main() {
s := []int{1, 2, 3}
s = append(s, s...)
fmt.Println(s) // [1, 2, 3, 1, 2, 3]
}Array Length Inference#
When using the [...] syntax in an array literal, the length of the array is automatically calculated based on the number of elements.
eg.
func main() {
a := [...]int{1, 2, 3}
fmt.Printf("%T\n", a) // [3]int
}