繼承
結構體
Go語言的結構體(struct)和其他語言的類(class)有同等的地位,但Go語言放棄了包括繼 承在內的大量面向對象特性,只保留了組合(composition)這個最基礎的特性。 組合甚至不能算面向對象特性,因為在C語言這樣的過程式編程語言中,也有結構體,也有組合。組合只是形成復合類型的基礎。
type Rect struct { x, y float64 width, height float64 }
簡單繼承
package main import ( "fmt" ) type Father struct { MingZi string } func (this *Father) Say() string { return "大家好,我叫 " + this.MingZi } type Child struct { Father } func main() { c := new(Child) c.MingZi = "小明" fmt.Println(c.Say()) }
多重繼承
package main import ( "fmt" ) type Father struct { MingZi string } func (this *Father) Say() string { return "大家好,我叫 " + this.MingZi } type Mother struct { Name string } func (this *Mother) Say() string { return "Hello, my name is " + this.Name } type Child struct { Father Mother } func main() { c := new(Child) c.MingZi = "小明" c.Name = "xiaoming" fmt.Println(c.Father.Say()) fmt.Println(c.Mother.Say()) }
名字沖突問題
package main import( "fmt" ) type X struct { Name string } type Y struct { X Name string //相同名字的屬性名會覆蓋父類的屬性 } func main(){ y := Y{X{"XChenys"},"YChenys"} fmt.Println("y.Name = ",y.Name) //y.Name = YChenys }
所有的Y類型的Name成員的訪問都只會訪問到最外層的那個Name變量,X.Name變量相當於被覆蓋了,可以用y.X.Name引用
接口
在Go語言中,一個類只需要實現了接口要求的所有函數,我們就說這個類實現了該接口,
根據《Go 語言中的方法,接口和嵌入類型》的描述可以看出,接口去調用結構體的方法時需要針對接受者的不同去區分,即:
- 接收者是指針*T時,接口實例必須是指針
- 接收者是值 T時,接口實力可以是指針也可以是值
- 接口的定義和類型轉換與接收者的定義是關聯的
接口繼承
栗子:
package main import ( "fmt" ) type Action interface { Sing() } type Cat struct { } type Dog struct { } func (*Cat) Sing() { fmt.Println("Cat is singing") } func (*Dog) Sing() { fmt.Println("Dog is singing") } func Asing(a Action) { a.Sing() } func main() { cat := new(Cat) dog := new(Dog) Asing(cat) Asing(dog) }
接口使用
栗子:
package main import "fmt" type Type struct { name string } type PType struct { name string } type Inter iInterface { post() } // 接收者非指針 func (t Type) post() { fmt.Println("POST") } // 接收者是指針 func (t *PType) post() { fmt.Println("POST") } func main() { var it Inter //var it *Inter //接口不能定義為指針 pty := new(Type) ty := {"type"} it = ty // 將變量賦值給接口,OK it.post() // 接口調用方法,OK it = pty // 把指針變量賦值給接口,OK it.post() // 接口調用方法,OK pty2 := new(PType) ty2 := {"ptype"} it = ty2 // 將變量賦值給接口,error it.post() // 接口調用方法,error it = pty2 // 把指針變量賦值給接口,OK it.post() // 接口調用方法,OK }
作者:吃貓的魚0
鏈接:https://www.jianshu.com/p/fe8c366dcd1d
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。