Src
Src

Reputation: 5482

Pointers in 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)?

Upvotes: 1

Views: 147

Answers (2)

Adam Smith
Adam Smith

Reputation: 54162

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\n", a, b)  // gives the same pointer value
}

Try it here

Upvotes: -1

uakf.b
uakf.b

Reputation: 151

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.

Upvotes: 6

Related Questions