Slices and underlying array

Hello. I am new here and hope it’s okay to ask that kind of question. In the first example, the slice2 acts as an independent array. On the second example it’s not the case. Why is that?

Thank you!

slice1 := []int{1}
slice1 = append(slice1, 3)
slice2 := append(slice1, 4)

slice2[0] = 7

fmt.Println(slice1) // 1 3
fmt.Println(slice2) // 7 3 4


slice1 := []int{1}
slice1 = append(slice1, 2)
slice1 = append(slice1, 3)
slice2 := append(slice1, 4)

slice2[0] = 7

fmt.Println(slice1) // 7 2 3
fmt.Println(slice2) // 7 2 3 4

Because in the first case, the underlying array hat to grow and a reallocation happened for slice2

For the second case the array didn’t need to grow, and therefore both slices point to the same start, but have a different length.

1 Like

Thank you!)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.