Home > OS >  Updating a parent structure reference golang
Updating a parent structure reference golang

Time:09-30

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.

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related