看程序:
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使用