Reputation: 5482
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
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
}
Upvotes: -1
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