Go语言类型判断:type-swtich

笔者之前写过一篇关于类型转换和类型断言,还有一个类似的语法叫类型判断: type-switch。该语法通过switch和关键字type的类型断言用来判断类型。

var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
    fmt.Printf("unexpected type %T\n", t)     // %T prints whatever type t has
case bool:
    fmt.Printf("boolean %t\n", t)             // t has type bool
case int:
    fmt.Printf("integer %d\n", t)             // t has type int
case *bool:
    fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
    fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
注: type-switch 只用于判断interface

代码来源: Effective Go

你可能感兴趣的:(Go语言类型判断:type-swtich)