value, ok := x.(T)
其中,x 表示一个接口的类型,T 表示一个具体的类型(也可为接口类型)。package main import ( "fmt" ) func main() { var x interface{} x = 10 value, ok := x.(int) fmt.Print(value, ",", ok) }运行结果如下:
10,true
需要注意如果不接收第二个参数也就是上面代码中的 ok,断言失败时会直接造成一个 panic。如果 x 为 nil 同样也会 panic。package main import ( "fmt" ) func main() { var x interface{} x = "Hello" value := x.(int) fmt.Println(value) }运行结果如下:
panic: interface conversion: interface {} is string, not int
类型断言还可以配合 switch 使用,示例代码如下:package main import ( "fmt" ) func main() { var a int a = 10 getType(a) } func getType(a interface{}) { switch a.(type) { case int: fmt.Println("the type of a is int") case string: fmt.Println("the type of a is string") case float64: fmt.Println("the type of a is float") default: fmt.Println("unknown type") } }运行结果如下:
the type of a is int
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有