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

Can you explain the behavior of this Go pointer manipulation?

package main
import "fmt"

type Item struct {
    val int
}

func main() {
    var items []*Item
    item := Item{}
    items = append(items, &item)
    x := items[0]
    y := *x
    x.val++
    fmt.Printf("x=%v, y=%v\n", *x, y)
}

This prints:

x={1}, y={0}

I can’t understand why the values are different. x is a pointer to the 1st element in the array, and we increment the val field using x, then the 1st element has been changed. y is the first element, and its val should’ve changed too, but didn’t? If, however, the y := *x statement is moved to after x.val++, then the values are equal. Why?

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 :

Only this line needs to be explained

y := *x

and it means to take value from this pointer (*x) and assign it to y, now y has a freshly non connected to x value.

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