pointersgostructmutators

Modifying field values to struct pointers in Go


New to Golang and trying to understand a code snippet I ran across. In the blog I was reading, they define a Vertex struct like so:

type Vertex struct {
  X int
  Y int
}

And then show an example of how to create a new instance of it and modify one of its fields:

v1 := Vertex{1,2}
v1.X = 3

However they they show an example of how to create a pointer to an instance of this struct and modify one of its fields:

v2 := &Vertex{3,4}
v2.X = 3

This has me a little confused. To me, the statement v2 := &Vertex{3,4} translates to: "v2 is a pointer to a new Vertex{3,4} instance". If that's true, then if v2 is a pointer to a Vertex struct, and not a Vertex struct itself, then how can we invoke v2.X on it (it's a pointer!!!)?


Solution

  • Accessing the struct fields using a pointer, you don't need dereferencing explicitly.

    That's why v2.X is same as (*v2).X

    Find more details here