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 語言中的方法,接口和嵌入類型》的描述能夠看出,接口去調用結構體的方法時須要針對接受者的不一樣去區分,即:post
栗子:ui
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) }
栗子:this
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 }