多态
265 字
1 分钟
多态
多态
接口
type Animal interface { Sleep() GetColor() string // 方法名:GetColor,返回:string GetType() string}具体类
type Cat struct { color string}
func (this *Cat) Sleep() { fmt.Println("Cat.Sleep()")}func (this *Cat) GetColor() string { return this.color}func (this *Cat) GetType() string { return "Cat"}
// ===================
type Dog struct { color string}
func (this *Dog) Sleep() { fmt.Println("Dog.Sleep()")}func (this *Dog) GetColor() string { return this.color}func (this *Dog) GetType() string { return "Dog"}main
func showAnimal(animal Animal) { animal.Sleep() fmt.Println("showAnimal.color:", animal.GetColor()) fmt.Println("showAnimal.type:", animal.GetType())}
func main() { // 多态 var animal Animal animal = &Cat{"Yello"} animal.Sleep() // Cat.Sleep()方法 fmt.Println(animal.GetColor()) fmt.Println(animal.GetType())
animal = &Dog{"Brown"} animal.Sleep() fmt.Println(animal.GetColor()) fmt.Println(animal.GetType())}-------------
Cat.Sleep()YelloCatDog.Sleep()BrownDogshowAnimal.color: whiteshowAnimal.type: Cat- 有一个父类(有接口)
- 有子类(实现父类的全部接口方法)
- 父类类型的变量(指针)指向(引用)子类的具体数据变量
通用万能类型

func myFunc(arg interface{}) { fmt.Println("my func is called...") fmt.Println(arg)
// 给 interface{} 提供“类型断言”的机制 value1, ok1 := arg.(string) if !ok1 { fmt.Println("arg is not a string type, value is", arg) } else { fmt.Println("arg is a string type, value is", value1) fmt.Printf("valye type is %T\n", value1) }
}
type Doge struct { name string age int}
func main() { dog := Doge{"Wangcai", 2} myFunc(dog)
myFunc(100) myFunc("absd") myFunc(3.213)}文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!
相关文章 智能推荐
1
函数多值返回
golang 函数多值返回
2
1 变量和常量
golang 1 变量和常量
3
2 输入输出
golang 2 输入输出
4
3 基本数据类型
golang 3 基本数据类型
5
4 数组、切片和Map
golang 4 数组、切片和Map
随机文章 随机推荐