• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    使用go的interface案例实现多态范式操作

    看程序:

    package main 
    import "fmt" 
    type BaseIntf interface {
     Process()
    }
     
    type Msg1 struct {
     req int
     rsp int
    }
     
    func (p *Msg1) Process() {
     fmt.Println("process 1")
    }
     
    type Msg2 struct {
     req int
     rsp int
    }
     
    func (p *Msg2) Process() {
     fmt.Println("process 2")
    }
     
    func main() {
     m1 := new(Msg1)
     m1.Process()
     
     m2 := new(Msg2)
     m2.Process()
    }

    变一下:

    package main 
    import "fmt" 
    type BaseIntf interface {
     Process()
    }
     
    func Run(proc BaseIntf) {
     fmt.Println("run")
     proc.Process()
    }
     
    type Msg1 struct {
     req int
     rsp int
    }
     
    func (p *Msg1) Process() {
     fmt.Println("process 1")
    } 
     
    type Msg2 struct {
     req int
     rsp int
    }
     
    func (p *Msg2) Process() {
     fmt.Println("process 2")
    } 
     
    func main() {
     m1 := new(Msg1)
     Run(m1)
     
     m2 := new(Msg2)
     Run(m2)
    }

    这种风格的代码,见了很多次了。

    不多说。

    补充:go语言中通过空接口查询来实现多态

    直接看代码吧~ 空接口算是go语言的精妙之处

    package main
    type Person struct {
     name string
     age int
    }
    type Cat struct {
     kind string
     sex bool
     price int
    }
    func main() {
     family := make([]interface{},0,10)
     obj1 := Person{
     name: "吕云飞",
     age: 28,
     }
     obj2 := Person{
     name: "胡景茹",
     age: 18,
     }
     obj3 := Cat{
     kind: "英短",
     sex: true,
     price: 2000,
     }
     family = append(family, obj1, obj2, obj3)
     for _, value := range family {
     switch obj := value.(type) {
     case *Person:
     print(obj.name + "\n")
     case *Cat:
     print(obj.kind + "\n")
     }
     }
    }

    输出结果如下

    吕云飞

    胡景茹

    英短

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

    您可能感兴趣的文章:
    • Go语言实现类似c++中的多态功能实例
    • golang语言如何将interface转为int, string,slice,struct等类型
    • golang基础之Interface接口的使用
    • golang struct 实现 interface的方法
    • golang中struct和interface的基础使用教程
    • Go之interface的具体使用
    • Go语言中你不知道的Interface详解
    • golang中interface接口的深度解析
    • 浅谈Go语言多态的实现与interface使用
    上一篇:go语言实现接口查询
    下一篇:对Golang中的runtime.Caller使用说明
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯 版权所有

    《增值电信业务经营许可证》 苏ICP备15040257号-8

    使用go的interface案例实现多态范式操作 使用,的,interface,案例,实现,