我試圖達到多態性這種方式GO多態性GO接口
type Discoverer interface {
Discover() string
}
type A struct {
}
func (obj A) GetTest() string {
return "im in A"
}
type B struct {
A
}
func (obj B) GetTest() string {
return "im in B"
}
func (obj A) Discover() string {
return obj.GetTest()
}
func main() {
a := A{}
b := B{}
fmt.Println(a.Discover())
fmt.Println(b.Discover())
}
現在我得到的輸出
im in A
im in A
所以,我的問題是:這是可能的見輸出
im in A
im in B
沒有「覆蓋」發現B?
func (obj B) Discover() string {
return obj.GetTest()
}
爲什麼?我有很多的結構小方法(類),發現漂亮的所有結構是相同的,所以我想避免複製粘貼&發現在每個結構(類)
去操場https://play.golang.org/p/nYc2hc3UbG
謝謝提前!
Go中沒有繼承(也沒有多態性)。一些相關/可能的重複:[one](http:// stackoverflow。它是可能調用重寫方法從父結構在Golang),[two](http://stackoverflow.com/questions/30622605/can-embedded -struct-method-have-knowledge-of-parent-child),[three](http://stackoverflow.com/questions/29390736/go-embedded-struct-call-child-method-instead-parent-method) ,[四](http://stackoverflow.com/questions/29144622/what-is-the-idiomatic-way-in-go-to-create-a-complex-hierarchy-of-structs)。 – icza