skip to content
Alvin Lucillo

Slices across functions

/ 1 min read

💻 Tech

In Go, passing a slice is pointer semantics, meaning that the underlying array can be modified by the called function. However, when the called function appends an item to the received slice, the changes won’t be visible in the calling function because their slices will have two different underlying arrays. This is why in the sample code below, “z” item isn’t in the output.

func main() {
	data := []string{"x", "y"}
	fmt.Println(data)
	change(data)
	fmt.Println(data)
}

func change(x []string) {
	x[0] = "a"
	x = append(x, "z")
}
[x y]
[a y]