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

时间:2022-12-28

浏览:488

作者:佚名

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《使用go的interface案例实现多态范式操作》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下多态、gointerface,希望所有认真读完的童鞋们,都有实质性的提高。

看程序:

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

输出结果如下

吕云飞

胡景茹

英短

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

今天关于《使用go的interface案例实现多态范式操作》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于golang的内容请关注golang学习网公众号!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页