Golang中的指针

Why this:

obj := *g
return &obj, nil

is not equal to this:

return &(*g), nil

Shouldn't it be working in the same way (Return pointer that is pointing to the new memory region with the data from g struct)?

In the first one, you allocate a new memory region by declaring obj. In the second, you simply reference the value at g, which is just g.

I'm not convinced that it's not the same.

package main

import "fmt"

type G struct {

}

func foo(g *G) (*G, error) {
  return &(*g), nil
}

func bar(g *G) (*G, error) {
  obj := (*g)
  return &obj, nil
}

func main() {
  g := &G{}

  a, _ := foo(g)
  b, _ := bar(g)

  fmt.Printf("a: %p, b: %p
", a, b)  // gives the same pointer value
}

Try it here