skip to content
Alvin Lucillo

Slicing shares backing array

/ 1 min read

Be careful with manipulating sliced values since slices are views into the same memory. Use slices.Clone to safely create a copy to manipulate:

func main() {
	a := []int{1, 2, 3, 4}
	b := a[1:3]
	b[0] = 99
	fmt.Println("a", a) // [1 99 3 4]

	c := slices.Clone(a[1:3])
	c[0] = 100
	fmt.Println("a", a) // [1 99 3 4] -- unchanged
	fmt.Println("c", c) // [100 3] -- has its own copy
}