Can someone help me understand why this happens like this? I would assume that the inheritance of a function would still work with a nil object. I'd ideally like to have child get use of the same bar function as a pointer if possible.
import "fmt"
type foo struct{}
func (this *foo) bar() string {
if this == nil {
return "I'm nil"
}
return "I'm NOT nil"
}
type child struct {
foo // inheret
}
func main() {
var obj *foo
fmt.Println(obj.bar()) // this works
var childObj *child
fmt.Println(childObj.bar()) // this seg faults
}
Here's a link to the playground as well.
CodePudding user response:
When using Go it's important to note that embedding !=
inheritance. And to understand the difference between the two if you want to use embedding to replace inheritance.
You can find some information about the difference between the two in Effective Go.
But, in my own words, this is what is happening in your example:
Writing childObj.bar()
is equivalent to writing childObj.foo.bar()
(accessing the foo
field of childObj
and then invoking its method bar()
). Because childObj
is nil
, trying to dereference it to access the field foo
will be a nil pointer error.