更新父结构引用 Golang

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

Updating a parent structure reference golang

问题

我是新手学习 Golang。我有一个例子在这里 - https://go.dev/play/p/lusSZk5be4b

我试图从同一个父结构的一个元素更新全局父结构。我原本以为这个程序可能会出问题,因为它从自己的子结构更新父结构,但实际上它似乎工作正常。

我不明白这是否是正确的行为,并且在 Golang 中是否被接受,或者说根本不应该这样从子结构更新父结构。任何帮助都将不胜感激。

谢谢。

英文:

I am new to Golang. I have this example here - https://go.dev/play/p/lusSZk5be4b

I am trying to update the global parent structure from one of the elements of the same parent structure. I was expecting this program might create an issue because of updating the parent structure from it's own child but this seems to work fine.

I did not understand if this is the right behaviour and is accepted in golang or this kind of updating the parent from child should not be done at all. Any help is appreciated.

Thank you.

答案1

得分: 2

你实际上并没有替换父对象,而是替换了全局变量。
如果你保留对原始父对象的引用,你会发现那里的情况保持不变:

https://go.dev/play/p/FsNVdheZPfE

func main() {
    p = &parent{}
    oldParent = p
    ...
    fmt.Pritnln(oldParent)
    ... 

即使在子结构体上有一个实际的父对象并对其进行更新(示例:https://go.dev/play/p/hELKFB7DWc-),原始引用仍将指向子对象,但子对象将具有没有子对象的父对象。

因此,总结起来,你只是更新了引用,这是完全有效的。无论这在代码中是否有意义,或者你可能会丢失一个重要的引用,这是另一回事。

英文:

You're not actually replacing the parent, but the global variable.
If you keep a reference to the original parent you'll see things remain the same there:

https://go.dev/play/p/FsNVdheZPfE

func main() {
	p = &parent{}
	oldParent = p
    ...
    fmt.Pritnln(oldParent)
    ... 

Even if you had an actual parent on the child struct and update it (example: https://go.dev/play/p/hELKFB7DWc- ) , the original reference would still have the child, but the child would have a parent with no children.

So in summary, you're just updating references which is totally valid. Whether that makes sense in code or you might lose an important reference that's a different thing.

huangapple
  • 本文由 发表于 2022年9月29日 22:22:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/73897158.html
匿名

发表评论

匿名网友

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

确定