类型断言提供对接口具体值的访问。

类型断言

interfaceinterface
x.(T)xTxnil
TinterfacexTTinterfacexT
var x interface{} = "foo"

var s string = x.(string)
fmt.Println(s)     // "foo"

s, ok := x.(string)
fmt.Println(s, ok) // "foo true"

n, ok := x.(int)
fmt.Println(n, ok) // "0 false"

n = x.(int)        // ILLEGAL
复制代码

输出:

panic: interface conversion: interface {} is string, not int
复制代码

类型切换

类型切换顺序执行多个类型声明,并使用匹配的类型运行第一种情况。

var x interface{} = "foo"

switch v := x.(type) {
case nil:
    fmt.Println("x is nil")            // here v has type interface{}
case int: 
    fmt.Println("x is", v)             // here v has type int
case bool, string:
    fmt.Println("x is bool or string") // here v has type interface{}
default:
    fmt.Println("type unknown")        // here v has type interface{}
}
复制代码

输出:

x is bool or string
复制代码