使用go的interface案例實(shí)現(xiàn)多態(tài)范式操作
更新時(shí)間:2020年12月23日 14:34:30 作者:濤歌依舊
這篇文章主要介紹了使用go的interface案例實(shí)現(xiàn)多態(tài)范式操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
看程序:
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) }
這種風(fēng)格的代碼,見(jiàn)了很多次了。
不多說(shuō)。
補(bǔ)充:go語(yǔ)言中通過(guò)空接口查詢來(lái)實(shí)現(xiàn)多態(tài)
直接看代碼吧~ 空接口算是go語(yǔ)言的精妙之處
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") } } }
輸出結(jié)果如下
呂云飛
胡景茹
英短
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:
- Go語(yǔ)言實(shí)現(xiàn)類似c++中的多態(tài)功能實(shí)例
- golang語(yǔ)言如何將interface轉(zhuǎn)為int, string,slice,struct等類型
- golang基礎(chǔ)之Interface接口的使用
- golang struct 實(shí)現(xiàn) interface的方法
- golang中struct和interface的基礎(chǔ)使用教程
- Go之interface的具體使用
- Go語(yǔ)言中你不知道的Interface詳解
- golang中interface接口的深度解析
- 淺談Go語(yǔ)言多態(tài)的實(shí)現(xiàn)與interface使用
相關(guān)文章
簡(jiǎn)介Go語(yǔ)言中的select語(yǔ)句的用法
這篇文章主要介紹了簡(jiǎn)介Go語(yǔ)言中的select語(yǔ)句的用法,是golang入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-10-10go語(yǔ)言寫的簡(jiǎn)要數(shù)據(jù)同步工具詳解
作為go-etl工具的作者,想要安利一下這個(gè)小巧的數(shù)據(jù)同步工具,它在同步百萬(wàn)級(jí)別的數(shù)據(jù)時(shí)表現(xiàn)極為優(yōu)異,基本能在幾分鐘完成數(shù)據(jù)同步,這篇文章主要介紹了go語(yǔ)言寫的簡(jiǎn)要數(shù)據(jù)同步工具,需要的朋友可以參考下2024-07-07Golang構(gòu)建WebSocket服務(wù)器和客戶端的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何使用Go語(yǔ)言構(gòu)建WebSocket服務(wù)器和客戶端,以實(shí)現(xiàn)雙向通信,文中的示例代碼講解詳細(xì),需要的小伙伴可以參考一下2023-11-11