skip to content
Alvin Lucillo

Slice gotcha

/ 1 min read

When you pass a slice to a function, you’re sharing the address of the underlying array of a slice, so after the function call you might see different slice values.

However, if the function appended a new value to the slice, the original slice won’t be affected; instead, you must work on the resulting value after the append if you need the new set of slice.

You’ll also notice that the capacity (not the length) of the returned slice doubled (the original slice has 3, the returned slice has 6)

func main() {
	x := []int{1, 2, 3}
	fmt.Println(x, cap(x)) // [1 2 3] 3
	y := mutateSlice(x)
	fmt.Println(x, cap(x)) // [1 0 3] 3
	fmt.Println(y, cap(y)) // [1 0 3 4] 6
	z := mutateSlice(y)
	fmt.Println(y, cap(y)) // [1 0 3 4] 6
	fmt.Println(z, cap(z)) // [1 0 3 4 4] 6
}

func mutateSlice(x []int) []int {
	x[1] = 0
	x = append(x, 4)
	return x
}