golang 中一切 皆是類型
這個和 面向對象的 概念有點像 ,但是又不太像,和javascript倒是有些相似之處
那麼如何實現 像 Java中的 繼承呢,golang使用的是組合
請看代碼 和 運行輸出 說明一切
type father struct {name string
sex int
}
type sun struct {
father
name string
}
func main() {
s:=sun{father:father{name:"father",sex:11},name:"sun"}
fmt.Println(s)
fmt.Println("name",s.name)
fmt.Println("name",s.father.name)
fmt.Println("sex",s.sex)
fmt.Println("sex",s.father.sex)
}
=======================================
{{father 11} sun}
name sun
name father
sex 11
sex 11
===================================
father的sex屬性就被組合進了sun ,成爲了sun的屬性,雖然我的 命名是 father和 sun但 二者不是繼承 是組合的關係
當father的屬性 和 sun的屬性同名,被組合者 即母體 sun優先,想要 訪問 father的name需要 s.father.name