Go: Variadic functions (...T)

If the last parameter of a function has type ...T like this:

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

...it can be called with any number of trailing arguments of type T.

fmt.Println(Sum())        // 0
fmt.Println(Sum(1, 2, 3)) // 6

The actual type of ...T inside the function is []T.

You can pass a slice s directly to a variadic funtion using the s... notation. In this case no new slice is created.

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

Append is variadic

As a special case, you can append a string to a byte slice using the built-in append function:

var buf []byte
buf = append(buf, 'a', 'b')
buf = append(buf, "cd"...)
fmt.Println(buf) // [97 98 99 100]


Be the first to comment!