Yes, you could have done v.X = 1e9
. That's the point of the example, v.X = 1e9
and p := &v; p.X = 1e9
are equivalent. It is a simple example to illustrate how pointers work. It isn't meant to be practical.
Pointers become very important once you start passing structs into methods. Let's say you wanted to write a method that set X. If we passed the struct as a value...
func (v Vertex) setX(newX int) {
v.X = newX
}
func main() {
v := Vertex{1, 2}
v.setX(1e9)
fmt.Println(v)
}
We get {1 2}
. It wasn't set. This is because Go copies values into methods. setX
works on a copy of your struct.
Instead, we pass a pointer.
func (v *Vertex) setX(newX int) {
v.X = newX
}
And now we get {1000000000 2}
. setX
is working on a pointer to your struct.
Note v.setX(1e9)
is really (&v).setX(1e9)
but Go translates for you.
Methods aren't the only place pointers are useful. When you want to work with the same data in multiple places, use a pointer.
See Methods: Pointers vs Values and A Tour Of Go: Methods.