英文:
Golang segmentation violation with inheritance
问题
有人可以帮我理解为什么会出现这种情况吗?我本以为函数的继承仍然可以在一个空对象上工作。如果可能的话,我希望子类能够使用与指针相同的bar函数。
import "fmt"
type foo struct{}
func (this *foo) bar() string {
if this == nil {
return "我是空对象"
}
return "我不是空对象"
}
type child struct {
foo // 继承
}
func main() {
var obj *foo
fmt.Println(obj.bar()) // 这个可以工作
var childObj *child
fmt.Println(childObj.bar()) // 这个会导致段错误
}
这里还有一个链接到playground。
英文:
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.
答案1
得分: 4
在使用Go语言时,重要的是要注意嵌入!=
继承的概念,并且要理解两者之间的区别,如果你想使用嵌入来替代继承。
你可以在Effective Go中找到一些关于两者之间区别的信息。
但是,用我的话来解释,在你的例子中发生了以下情况:
写childObj.bar()
等同于写childObj.foo.bar()
(访问childObj
的foo
字段,然后调用它的方法bar()
)。因为childObj
是nil
,尝试解引用它来访问字段foo
将导致空指针错误。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论