go采坑记: golang 空接口的小技巧应用

最近在用golang写一个框架,希望可以比较灵活地构建一个方法,可以接受任意类型的输入,这样首先想到的是使用空接口interface{},因为在golang里面没有泛型。
空接口例子一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type download interface {
Download(interface{})
}

type dl struct {
t string
}

func (d dl) Download(a interface{}) {
switch a.(type) {
case string:
v := a.(string)
log.Println(v)
case int:
v := a.(int)
log.Println(v * v)
default:
}

}

空接口例子二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
type pool struct {
function interface{}
flag string
}

func (p *pool) RUN() {
s := p.function.(download)
s.Download("a")
s.Download(1)
}

func main() {
p := &pool{
function: &dl{},
}
p.RUN()
}