Last Updated: February 25, 2016
·
4.188K
· ihcsim

Appending Two Slices In Go (What's With That `...`?)

This is how one can append two slices in Go:

slice1 := []int{0, 1, 2, 3, 4}
slice2 := []int{5, 6, 7, 8}
fmt.Println(append(slice1, slice2...))

Running the above codes will produce:

[0 1 2 3 4 5 6 7 8]

Notice that the ... appended to slice2 tells the compiler to treat slice2 as a list of argument. If we removed the ..., changing the function calls to look like:

fmt.Println(append(slice1, slice2))

the compiler will complain saying that it cannot use slice2 (type []int) as type int in append.

Taking a look at the signature of append yields further clue.

func append(slice []Type, elems ...Type) []Type

Our above function calls tell the compiler that our Type is int. So unless we append ... to slice2, the compiler will raise a "type mismatch error", expecting its after-first argument to be an arbitrary number of variables of type int, but instead being given a variable of type []int.