Home > Software engineering >  Can you explain the behavior of this Go pointer manipulation?
Can you explain the behavior of this Go pointer manipulation?

Time:12-15

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?

CodePudding user response:

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.

CodePudding user response:

Because x is already a pointer to a Item. Try just y := x

  • Related