💻 Tech
To safely copy slices, you need to use the copy
function because slices use pointer semantics as it’s tracking the underlying data under the hood. In the example below, just copying the slice to another won’t do as the new allocation will refer to the same memory location of data. When you change the new allocation, it will affect the original data.
func main() {
letters1 := []string{"x", "y", "z"}
fmt.Println("letters1:")
fmt.Println(letters1)
letters2 := letters1
letters2[0] = "a"
fmt.Println("letters1 and letters2 after change to letters2:")
fmt.Println(letters1)
fmt.Println(letters2)
letters1 = []string{"x", "y", "z"}
letters3 := make([]string, len(letters1))
copy(letters3, letters1)
letters3[0] = "a"
fmt.Println("letters1 and letters3 after change to letters3:")
fmt.Println(letters1)
fmt.Println(letters3)
}
letters1:
[x y z]
letters1 and letters2 after change to letters2:
[a y z]
[a y z]
letters1 and letters3 after change to letters3:
[x y z]
[a y z]