v, ok = x.(T)// x: 表示类型为interface{}的变量// T: 表示断言x可能是的类型。// v: x转化为T类型后的变量// ok: bool值, 表示断言成功或失败
func main() {var x interface{}x = "pprof.cn"v, ok := x.(string)if ok {fmt.Println(v)} else {fmt.Println("类型断言失败")}}
如果要断言多次就需要写多个if判断,这个时候我们可以使用switch语句来实现:
func justifyType(x interface{}) {switch v := x.(type) {case string:fmt.Printf("x is a string,value is %v\n", v)case int:fmt.Printf("x is a int is %v\n", v)case bool:fmt.Printf("x is a bool is %v\n", v)default:fmt.Println("unsupport type!")}}
