-3

From tutorial in tour of go -

package main

import "fmt"

type Vertex struct {
    X int
    Y int
}

func main() {
    v := Vertex{1, 2}
    p := &v
    p.X = 1e9
    fmt.Println(v)
}

I can just do v.X to get the same value instead of assigning a pointer (p = &v and then p.X). Is there a design pattern that'd be coming up later for the same?

Volker
  • 40,468
  • 7
  • 81
  • 87
Saurabh Agrawal
  • 162
  • 2
  • 13
  • I this [question](https://stackoverflow.com/questions/59964619/difference-using-pointer-in-struct-fields) explain your question or at least a very similar one. – Gealber Nov 16 '20 at 09:30
  • 5
    Just take the full Tour of Go. Pointers are really simple, there is nothing to worry about, most of the time it just doesn't matter and when it matters it is obvious. – Volker Nov 16 '20 at 09:31
  • Thanks @Volker, I am just starting out with it and it is quite different from dynamically typed language JS that i am used to. – Saurabh Agrawal Nov 16 '20 at 09:44

1 Answers1

1

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.

Schwern
  • 153,029
  • 25
  • 195
  • 336
  • Thanks @Schwenn ! I'll be reaching to methods in tour of go soon and then i think it'll all start making more sense to me. In JS I'll define an object and start passing copies of that object for immutability. – Saurabh Agrawal Nov 16 '20 at 09:54