复制原始对象后仍在修改。

huangapple go评论74阅读模式
英文:

After copying the original object is still being modified

问题

在上面的代码中,为什么会修改n的值?(playground链接

package main

import (
	"fmt"
	"math/big"
)

func main() {
	n := big.NewInt(5)
	nCopy := new(big.Int)
	*nCopy = *n

    // 预期 "n" 和 "nCopy" 的值应该相同。
	fmt.Println(n.String(), nCopy.String(), &n, &nCopy)

	nCopy.Mod(nCopy, big.NewInt(2))

    // 预期 "n" 和 "nCopy" 的值应该不同。
	fmt.Println(n.String(), nCopy.String(), &n, &nCopy)
}

阅读这个答案,似乎说我示例中main()函数的第三行应该复制n的内容。两个Println语句输出的变量地址似乎也表明这两个big.Int存储在不同的内存位置。

我意识到,我可以使用nCopy.Set(n)代替*nCopy = *n,这样我的最后一个Println将显示我期望的结果。但我很好奇为什么*nCopy = *n似乎保留了两个指针之间的"链接"。

英文:

In the following code why is the value of n being modified? (playground link)

package main

import (
	"fmt"
	"math/big"
)

func main() {
	n := big.NewInt(5)
	nCopy := new(big.Int)
	*nCopy = *n

    // The values of "n" and "nCopy" are expected to be the same.
	fmt.Println(n.String(), nCopy.String(), &n, &nCopy)

	nCopy.Mod(nCopy, big.NewInt(2))

    // The values of "n" and "nCopy", I would think, should be different.
	fmt.Println(n.String(), nCopy.String(), &n, &nCopy)
}

Reading this answer seems to say that the third line in my example's main() should make a copy of the contents of n. The addresses of the two variables which are output in the two Println statements also seem to show that the two big.Ints are stored in separate memory locations.

I realize that instead of using *nCopy = *n I could use nCopy.Set(n) and my final Println would display what I expect it to. But I am curious why *nCopy = *n seems to retain a "link" between the two pointers.

答案1

得分: 2

一个Int是一个带有nat字段的结构体。nat是一个切片。

当你复制Int时,原始Int和副本共享nat的后备数组。通过一个Int对后备数组的修改对另一个Int可见。

赋值不是深拷贝。对结构体值的赋值等同于逐个赋值结构体中的字段。对切片的赋值不会复制后备数组。

英文:

An Int is a struct with a nat field. A nat is a slice.

When you copy the Int, the original and copy share the backing array for the nat. Modifications through one Int to the backing array are visible to the other Int.

Assignment is not a deep copy. Assignment of a struct value is equivalent to assigning the fields in the struct individually. Assignment of a slice does not copy the backing array.

huangapple
  • 本文由 发表于 2014年10月12日 09:30:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/26320964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定