Go语言之面向对象-多态与类型断言

Posted 程序彤

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go语言之面向对象-多态与类型断言相关的知识,希望对你有一定的参考价值。

类型断言

使用方法:
接口实例.(具体结构体子类)。
综合使用:
if 子类实例名,ok := 接口实例.(子类);ok{如果true子类实现了该接口,即进行一系列处理}

	// 调用猫猫特有的喵喵方法。
	if cat,ok := animal.(Cat);ok{ // 如果类型断言是cat成功
		cat.Miao()
	}
package main

import "fmt"

func main() {
	//zoo:=Zoo{}
	//cat:=Cat{}
	//dog:=Dog{}
	//
	 多态
	//zoo.coming(cat)
	//zoo.coming(dog)
	var animalArr [3]Animal2
	animalArr[0] = Cat{"小橘"}
	animalArr[1] = Dog{"二哈"}
	animalArr[2] = Dog{"哈皮狗"}

	// 遍历自定义类型数组
	var zoo Zoo
	for _,v:=range animalArr{
		zoo.coming(v)
	}
}

/*
动物
*/
type Animal interface {
	Shout() // 叫
	Eat() // 吃

}
/*
猫狗的吃叫方法也隐式实现了这个接口
定义好的接口,我就放这,你若实现了我接口中的所有方法,你这个结构体就是实现了接口。
*/

type Animal2 interface {
	Shout() // 叫
	Eat() // 吃
}

/*
猫
*/
type Cat struct {
	Name string
}

func (cat Cat) Shout(){ // 都不知道这个方法属于Animal这个接口。。
	fmt.Println(cat.Name,"猫猫叫。。。")
}

func (cat Cat) Eat(){
	fmt.Println(cat.Name,"猫猫吃。。。")
}
func (cat Cat) Miao(){
	fmt.Println(cat.Name,"miao~~~")
}

/*
狗
*/
type Dog struct {
	Name string
}

func (dog Dog) Shout(){
	fmt.Println(dog.Name,"狗狗叫。。。2")
}

func (dog Dog) Eat(){
	fmt.Println(dog.Name,"狗狗吃。。。")
}

/*
动物园
*/
type Zoo struct {

}

/*
动物园
*/
func (zoo Zoo) coming(animal Animal2){
	// 通过接口调用
	animal.Shout()

	// Cat特有的Miao()方法这里无法直接调用。解决:类型断言
	if cat,ok := animal.(Cat);ok{ // 如果类型断言是cat成功
		cat.Miao()
	}

	animal.Eat()
}

在这里插入图片描述

案例二:
类型断言,循环判断传入参数的类型

package main

import "fmt"

func main() {
	var n1 float64 = 2.3
	var n2 int = 1
	var name string = "lwt"
	address := "北京"

	stu1 := Stu{}
	stu2 := &Stu{}

	TypeJudge(n1,n2,name,address,stu1,*stu2)

}

func TypeJudge(items ...interface{}) {
	for index, v := range items {
		switch v.(type) {
		case bool:
			fmt.Printf("第%v个参数是bool类型,值是%v\\n", index, v)
		case float64:
			fmt.Printf("第%v个参数是float64类型,值是%v\\n", index, v)
		case int,int32,int64:
			fmt.Printf("第%v个参数是整类型,值是%v\\n", index, v)
		case string:
			fmt.Printf("第%v个参数是string类型,值是%v\\n", index, v)
		case Stu:
			fmt.Printf("第%v个参数是Stu类型,值是%v\\n", index, v)
		case *Stu:
			fmt.Printf("第%v个参数是Stu类型,值是%v\\n", index, v)
		default:
			fmt.Printf("第%v个参数的类型不确定,值是%v\\n",index,v)
		}
	}
}

type Stu struct {

}


在这里插入图片描述

以上是关于Go语言之面向对象-多态与类型断言的主要内容,如果未能解决你的问题,请参考以下文章

[Golang]面向对象营养餐,一文管够(封装,继承,多态)

15. 面向对象编程:接口与多态

通学go语言系列之面向对象

『GoLang』面向对象

go语言学习面向对象oop

Go语言开发Go语言面向接口