Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When setting the pointer to nil, struct pointer field doesn't change

I have this code:

type X struct {
    y *X
}

func main() {
    x1 := &X{y: nil}
    x2 := &X{y: x1}

    fmt.Println(x1 == x2.y)
    // true

    x1 = nil

    fmt.Println(x1 == nil)
    fmt.Println(x2.y == nil)

    // true
    // false
}

As you can see x.y is a *X.
Why after setting x1 to nil. The value of x2.y doesn’t become nil?
Sorry if my question is so silly.

Here is the link of the code in Go playground.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

x1 is a pointer pointing to an {y:nil} of type X.
x2.y is also a pointer pointing to the same {y:nil}. So when you set x1=nil, x1 becomes a pointer that is nil, and x2.y is still pointing to the same {y:nil} object.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading