GO类型查询

来源:互联网 发布:看电影用什么软件最好 编辑:程序博客网 时间:2024/06/06 14:07

A type switch compares types rather than values. It is otherwise similar to an expression switch. It is marked by a special switch expression that has the form of a type assertion using the reserved word type rather than an actual type:

switch x.(type) {// cases}
Cases then match actual types T against the dynamic type of the expression x. As with type assertions, x must be of interface type, and each non-interface type T listed in a case must implement the type of x. The types listed in the cases of a type switch must all be different.


The type in a case may be nil; that case is used when x is  a nil interface value. There may be at most one nil case.

Given an expression x of type interface{}, the following type switch:

switch i := x.(type) {case nil:printString("x is nil")                // type of i is type of x (interface{})case int:printInt(i)                            // type of i is intcase float64:printFloat64(i)                        // type of i is float64case func(int) float64:printFunction(i)                       // type of i is func(int) float64case bool, string:printString("type is bool or string")  // type of i is type of x (interface{})default:printString("don't know the type")     // type of i is type of x (interface{})}
could be rewritten:

v := x  // x is evaluated exactly onceif v == nil {i := v                                 // type of i is type of x (interface{})printString("x is nil")} else if i, isInt := v.(int); isInt {printInt(i)                            // type of i is int} else if i, isFloat64 := v.(float64); isFloat64 {printFloat64(i)                        // type of i is float64} else if i, isFunc := v.(func(int) float64); isFunc {printFunction(i)                       // type of i is func(int) float64} else {_, isBool := v.(bool)_, isString := v.(string)if isBool || isString {i := v                         // type of i is type of x (interface{})printString("type is bool or string")} else {i := v                         // type of i is type of x (interface{})printString("don't know the type")}}
注意:The "fallthrough" statement is not permitted in a type switch.

0 0
原创粉丝点击