1 回答
TA贡献1807条经验 获得超9个赞
问题是您的结构包含切片,这些切片基本上是指向内存的指针。复制这些指针意味着您的副本指向与原始内存相同的内存,因此它们共享切片值。改变一个就会改变另一个。
这是一个小例子来说明这个问题:
package main
import "fmt"
type s struct {
a int
slice []int
}
func main() {
// create the original thing
prev := s{
a: 5,
slice: []int{1, 2, 3},
}
// copy the thing into cur
cur := prev
// now change cur, changing a will change only cur.a because integers are
// really copied
cur.a = 6
// changing the copied slice will actually change the original as well
// because copying a slice basically copies the pointer to memory and the
// copy points to the same underlying memory area as the original
cur.slice[0] = 999
// printing both, we can see that the int a was changed only in the copy but
// the slice has changed in both variables, because it references the same
// memory
fmt.Println(prev)
fmt.Println(cur)
}
- 1 回答
- 0 关注
- 99 浏览
添加回答
举报