switch {{ 推断后的变量 }}:={{ 接口变量 }}.(type){
case {{ 推断类型1 }}:
...
case {{ 推断类型2 }}:
...
default:
...
}
对于参数类型不确定的情况,推荐使用方式三
例子:通过类型推断对接口变量进行格式转换
package main
import "fmt"
func main() {
var i interface{}
// 类型推断方式一
i = 666
var v1 int
v1 = i.(int)
fmt.Printf("int:%d\n", v1)
// 类型推断方式二
i = "hello"
var v2 string
v2, ok := i.(string)
if !ok{
panic("not a string type")
}
fmt.Printf("string:%s\n", v2)
// 类型推断方式三
i = 3.1415926
var v3 float64
switch v:=i.(type){
case float64:
v3 = v
default:
panic("not type of float64")
}
fmt.Printf("float:%f\n", v3)
}