继承
结构体
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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。