Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize pointer receiver in pointer method Go

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?

like image 904
Francis Avatar asked Mar 17 '17 10:03

Francis


1 Answers

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.

like image 106
Flimzy Avatar answered Sep 22 '22 21:09

Flimzy