博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Go语言的多态(Polymorphism)
阅读量:6991 次
发布时间:2019-06-27

本文共 1255 字,大约阅读时间需要 4 分钟。

Go的多态(Polymorphism) 是怎么实现的?

这几天查资料下面的代码写的很容易看懂。

看代码吧。不多解释了.

package mainimport "fmt"type AnimalIF interface {    Sleep()    Age() int    Type() string}type Animal struct {    MaxAge int}/*=======================================================*/type Cat struct {    Animal Animal}func (this *Cat) Sleep() {    fmt.Println("Cat need sleep")}func (this *Cat) Age() int {    return this.Animal.MaxAge}func (this *Cat) Type() string {    return "Cat"}/*=======================================================*/type Dog struct {    Animal Animal}func (this *Dog) Sleep() {    fmt.Println("Dog need sleep")}func (this *Dog) Age() int {    return this.Animal.MaxAge}func (this *Dog) Type() string {    return "Dog"}/*=======================================================*/func Factory(name string) AnimalIF {    switch name {    case "dog":        return &Dog{Animal{MaxAge: 20}}    case "cat":        return &Cat{Animal{MaxAge: 10}}    default:        panic("No such animal")    }}/*======================================================*/func main() {    animal := Factory("dog")    animal.Sleep()    fmt.Printf("%s max age is: %d", animal.Type(), animal.Age())}
> Output:Dog need sleepDog max age is: 20

 

转载于:https://www.cnblogs.com/li-mingxie/p/6928557.html

你可能感兴趣的文章
windows 2003 下IIS没有ASP.NET 1.1.4322选项卡
查看>>
TP-Link 普联 TL-PA201 及TL-PWA2801N配对配置过程
查看>>
windows phone8 相比windows phone7中不同
查看>>
DDD~基础设施层
查看>>
Struts+iBatis+Spring+mysql整合开发
查看>>
将C++里的Mat矩阵保存并由matlab提取分析
查看>>
从程序员到项目经理(14):项目经理必须懂一点“章法”
查看>>
linux系统监控示例:vmstat
查看>>
Lock关键字的用法
查看>>
Automatic Tuning of Undo Retention
查看>>
Android 程序清单文件详解
查看>>
NFS挂载文件系统:unable to get mount port number from server, using default
查看>>
Attributes
查看>>
hdu 1270
查看>>
扩展整数poj 1061 青蛙的约会 扩展欧几里得
查看>>
c64x+ DSP/BIOS硬件中断的配置
查看>>
An in-place algorithm for String Transformation
查看>>
Linux进程控制
查看>>
Android更新下载进度条
查看>>
水印控件windows phone中,制作一个自定义的密码输入框控件,含图片,有水印,星号显示...
查看>>