使用go的interface案例實現多型正規化操作
阿新 • • 發佈:2020-12-24
看程式:
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{},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") } } }
輸出結果如下
呂雲飛
胡景茹
英短
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。