看程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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()
}
|
变一下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
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语言的精妙之处
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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")
}
}
}
|
输出结果如下
吕云飞
胡景茹
英短
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/stpeace/article/details/83868186