Golang类型switch
语法强迫症
在群里讨论到了这个问题
然后下面这是官方给出的例子
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T", 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
}
里面有几点要注意一下
在switch t := t.(type)
时
switch
的其实是t.(type)
而不是被创建的t
然后t := t.(type)
创建的是类型为t.(type)
,值为t
的值的一个变量
里面所使用的t
都是switch
里新建的那个t
等于下面这个例子
var t interface{}
t = functionOfSomeType()
switch t.(type) {
default:
fmt.Printf("unexpected type %T", t) // %T prints whatever type t has
case bool:
t := t.(bool)
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
t := t.(int)
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
t := t.(*bool)
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
t := t.(*int)
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}