How can I initialize a pointer receiver with a pointer method in Go?


Lets go!!

Published · Feb 6

package main import "fmt" type Person struct { name string age int } func (p *Person) Born() { if nil == p { p = new(Person) } } func main() { var person *Person person.Born() if person == nil { fmt.Println("This person should be initialized. Why is that not the case?") } fmt.Println(person) }

One would expect person to be initialized (zeroed) after calling .Born() method which is a pointer receiver. But that is not the case. Could someone shed some light on this?

Write your answer...

Never miss a post from Gopher , when you sign up for Ednsquare.