Golang继承时出现分段错误。

huangapple go评论59阅读模式
英文:

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()(访问childObjfoo字段,然后调用它的方法bar())。因为childObjnil,尝试解引用它来访问字段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.

huangapple
  • 本文由 发表于 2022年8月8日 10:10:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/73272339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定