Go采坑记: Golang 空接口的小技巧应用

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

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:
}

}

空接口例子二:

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()
}
shikanon wechat
欢迎您扫一扫,订阅我滴↑↑↑的微信公众号!