How can I initialize a pointer receiver with a pointer method?
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?
One would expect person to be initialized (zeroed) after calling .Born() method which is a pointer receiver.
Calling a method on a receiver assumes that the receiver is already initialized.
So you need to initialize it:
var person *Person
person = &Person{} // Sets the pointer to point to an empty Person{} struct
Or in a single statement:
var person = &Person{}
Or shorthand:
person := &Person{}
The reason your intended self-initialization is failing:
func (p *Person) Born() {
if nil == p {
p = new(Person)
}
}
Is that your new assignment to p
is scoped to the Born()
function, so outside the function it has no effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With