点击上方蓝色“Go语言中文网”关注我们,领全套Go资料,每天学习 Go 语言
本文作者:appleboy
原文链接:https://blog.wu-boy.com/2019/11/four-tips-with-select-in-golang/
本文带大家认识 Go 语言的 Select 用法,相信大家对于 switch 并不陌生,然而 select 跟 switch 有个共同特性就是都通过 case 的方式来处理,但是 select 跟 switch 处理的事情完全不同,也完全不相容。来看看 switch 有什么特性: 各种类型及型别操作,接口 interface{} 型别判断 variable.(type),重点是会依照 case 顺序依序执行。先看个例子:
package main
var (
i interface{}
)
func convert(i interface{}) {
switch t := i.(type) {
case int:
println("i is interger", t)
case string:
println("i is string", t)
case float64:
println("i is float64", t)
default:
println("type not found")
}
}
func main() {
i = 100
convert(i)
i = float64(45.55)
convert(i)
i = "foo"
convert(i)
convert(float32(10.0))
}
运行出来的结果如下:
i is interger 100
i is float64 +4.555000e+001
i is