-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?

3
  • I this question explain your question or at least a very similar one. Commented Nov 16, 2020 at 9: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. Commented Nov 16, 2020 at 9: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. Commented Nov 16, 2020 at 9:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.