类型判断
Go 语言中,一个接口类型 interface{} 可以存储其他任何类型(如 int, string, byte 等)的值。
而且 Go 语言中提供的容器 list,其节点的值类型就是 interface{},它不可以被直接使用。
type Element struct {next, prev *Elementlist *ListValue interface{} // !!!}
我们可以通过类型断言来确定一个接口类型的变量是否包含了某个类型的值。
var i interface{} = "abc"if s, ok := i.(string); ok {fmt.Printf("i has a string value %s", s)}
type-switch
type-switch 也是一种检测接口变量的类型的有效方法。
比如我们希望检测一个 []interface{} 数组里面每一元素的值:
func getType(test []interface{}) {for _, t := range test {switch t.(type) {case int:fmt.Printf("type %T with value %v\n", t, t)case float64:fmt.Printf("type %T with value %v\n", t, t)case rune:fmt.Printf("type %T with value %c\n", t, t)case string:fmt.Printf("type %T with value %v\n", t, t)case nil:fmt.Printf("type %T with value %v\n", t, t)default:fmt.Printf("unknown type\n")}}}
