Golang - Append two arrays or slices
Appending is a really common operation when programming, but how do we append two arrays / slices in Golang?
Well, first lets try it:
myStringSlice := []string{"first", "second", "third"}
myStringSlice = append(myStringSlice, []string{"fourth", "fift"})
But this error pops up:
cannot use []string literal (type []string) as type string in append
Then how do we do this? We could iterate with a for but it doesn’t look nice.
The alternative option to append on arrays / slices in GoLang is to add the “…” syntax after the array / slice:
myStringSlice := []string{"first", "second", "third"}
//ERROR!
//myStringSlice = append(myStringSlice, []string{"fourth", "fift"})
myStringSlice = append(myStringSlice, []string{"fourth", "fift"}...)
myStringSlice = append(myStringSlice, "sixth", "seventh")
fmt.Println(myStringSlice))
Under the hood
“…” is syntax for variadic arguments in Go, aka it changes an slice into a multiple arguments in the function call