多态

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()
Yello
Cat
Dog.Sleep()
Brown
Dog
showAnimal.color: white
showAnimal.type: Cat
  1. 有一个父类(有接口)
  2. 有子类(实现父类的全部接口方法)
  3. 父类类型的变量(指针)指向(引用)子类的具体数据变量

通用万能类型#

image.png
image.png

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)
}

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

多态
https://shaio.top/posts/丫丫学语/golang/多态/
作者
沙海
发布于
2026-08-10
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
沙海
Hello, I'm Shai.
公告
欢迎来到我的博客!这是一则示例公告。
音乐
封面

音乐

暂未播放

0:00 0:00
暂无歌词
分类
标签
站点统计
文章
84
分类
15
标签
48
总字数
67,035
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
GitHub Actions
博客版本
Firefly v6.12.2
文章许可
CC BY-NC-SA 4.0

文章目录