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 }