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

Issue

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.

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.

Answered By – Burak Serdar

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.