英文:
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.Int
s 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论