package main import "fmt" func test(a interface{}){ // 将接口类型的变量转化为具体类型 加个OK 判断, 可以避免程序直接崩溃, ok=false 转行失败 s,ok := a.(int) // 所以要加ok 判断, 对于不是int类型的, 会直接崩溃 panic: interface conversion: interface {} is string, not int if !ok { fmt.Printf("%v can't vonvert to int\n",s) } if ok { fmt.Println(s) return } str, ok := a.(string) if ok{ fmt.Println(str) return } f, ok := a.(float32) if ok{ fmt.Println(f) return } fmt.Println("can not define type of a") } func testInterface1(){ var a int =100 test(a) var b string = "hello world" test(b) // panic: interface conversion: interface {} is string, not int } // 缺点是要转2次 func testSeitch(a interface{}){ switch a.(type){ case string: fmt.Printf("a is string, value :%v\n",a.(string)) case int: fmt.Printf("a is int, value :%v\n",a.(int)) case int32: fmt.Printf("a is int32, value :%v\n",a.(int32)) default: fmt.Println("not support type\n") } } func testInterface2(){ var a int =100 testSeitch(a) var b string = "hello " testSeitch(b) } // 更推荐使用这个 func testSeitch2(a interface{}){ switch v := a.(type){ case string: fmt.Printf("a is string, value :%v\n",v) case int: fmt.Printf("a is int, value :%v\n",v) case int32: fmt.Printf("a is int32, value :%v\n",v) default: fmt.Println("not support type\n") } } func testInterface3(){ var a int =100 testSeitch2(a) var b string = "hello " testSeitch2(b) } func main() { testInterface1() testInterface2() testInterface3() }
输出:
100 0 can't vonvert to int hello world a is int, value :100 a is string, value :hello a is int, value :100 a is string, value :hello