Sobes.tech
Senior

Why is the copy operation needed for slices? Why can't you just assign one slice to another?

sobes.tech AI

Answer from AI

In Go, a slice is a structure that contains a pointer to an array, a length, and a capacity. When you assign one slice to another, only the slice structure is copied, but both slices point to the same underlying array.

Therefore, a simple assignment does not create a copy of the data, but only creates a new slice that references the same elements. Changes through one slice will affect the other.

The copy operation is used to copy elements from one slice to another, allocating a separate array so that changes in one slice do not affect the other.

Example:

src := []int{1, 2, 3}
dst := make([]int, len(src))
copy(dst, src) // copying data

// now dst and src are independent
src[0] = 10
fmt.Println(dst[0]) // 1

Without copy, assigning:

a := []int{1, 2, 3}
b := a
b[0] = 10
fmt.Println(a[0]) // 10 — the original slice has changed

Thus, copy is used to create an independent copy of the slice data.

Why is the copy operation needed for slices? Why… - sobes.tech