看程序:
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")
}
}
}
输出结果如下
吕云飞
胡景茹
英短
以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。如有错误或未考虑完全的地方,望不吝赐教。