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 關注
- 137 瀏覽
添加回答
舉報