golang-多态

空接口

先看个fmt包中的方法 Println,(经常用来打印输出的)

func Println(a ...interface{}) (n int, err error) {
	return Fprintln(os.Stdout, a...)
}

这里的 interface{} 就是一个空接口,它表示可以接受任意对象;在go中空接口也是一中数据类型(有点类似java中的Object)

func main() {
	var i interface{} = 45
	i=[...]int{1,2,3}
	fmt.Println(i)
}

接口的定义

在接口中可以定义一些通用的方法(不用实现)

type annimal interface {
	eat()
	sleep()
	run()
}

接口的继承与实现

接口的继承与实现也是将被继承和实现的接口以匿名属性传入即可

package main

import "fmt"

type annimal interface {
	eat()
	sleep()
	run()
}

type cat interface {
	annimal
	Climb()
}

type HelloKitty struct {
	cat
}

func (h HelloKitty)eat(){
	fmt.Println("eat cake!!")
}

func main() {
	var a annimal
	a = HelloKitty{}
	a.eat()
}

其中cat 继承了接口annimal ,HelloKitty实现了cat接口;不必将所有的方法都实现(这个和java不同)

多态

有了接口就可以实现多态了

package main

import "fmt"

type annimal interface {
	eat()
	sleep()
	run()
}

type cat interface {
	annimal
	Climb()
}
type dog interface {
	annimal
}

type HelloKitty struct {
	cat
}
type husky struct {
	dog
}

func (h HelloKitty)eat(){
	fmt.Println("eat cake!!")
}

func (h husky)eat(){
	fmt.Println("eat bone!!")
}

func test(a annimal){
	a.eat()
}

func main() {
	var a annimal
	a = HelloKitty{}
	test(a)
	a = husky{}
	test(a)
}

test方法中传入了一个animal对象,在实际调用时会因传入对象的不同而得到不同的效果
结果:

eat cake!!
eat bone!!

类型断言

判断具体的类型,在go中可以使用 对象.(指定的类型) 判断改对象是否时指定的类型

func main() {
	var a annimal
	a = HelloKitty{}
	var b annimal
	b = husky{}

	var animals [2]annimal =[...]annimal{a,b}

	for _,v :=range animals{
		if data,ok :=v.(husky);ok{
			data.eat()
			fmt.Println("this is wangcai : ")
		}
		if data,ok :=v.(HelloKitty);ok{
			data.eat()
			fmt.Println("this is HelloKitty : ")
		}
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_37910453/article/details/86645233