What is '...' in Go

In Golang, an ellipsis (...) is a syntax element that can be used in several contexts:

  1. Variadic Functions: When used as a parameter in a function definition, it allows the function to accept a variable number of arguments of the same type. For example, the following function definition accepts an arbitrary number of integers as arguments:

func sum(nums ...int) int {
    total := 0
    for _, num := range nums {
        total += num
    }
    return total
}
  1. Variadic Slices: When used in a function call, it can be used to "unpack" a slice and pass its elements as separate arguments. For example, the following function call passes each element of the nums slice as a separate argument to the sum function:

nums := []int{1, 2, 3, 4, 5}
total := sum(nums...)
  1. Variadic Types: The ellipsis can also be used in the definition of a struct or array to indicate that the size of the struct or array is variable. For example, the following array definition creates an array of integers with a length that is determined at runtime:

var nums [3]int
var nums [...]int{1, 2, 3, 4, 5}

In all cases, the ellipsis indicates that there may be an arbitrary number of values of a certain type.

Last updated