golang还有一种特殊形式来检测接口变量的类型—swtich:

    1. switch t := areaIntf.(type) {
    2. case *Square:
    3. fmt.Printf("Type Square %T with value %v\n", t, t)
    4. case *Circle:
    5. fmt.Printf("Type Circle %T with value %v\n", t, t)
    6. case nil:
    7. fmt.Printf("nil value: nothing to check?\n")
    8. default:
    9. fmt.Printf("Unexpected type %T\n", t)
    10. }

    如果仅仅是测试变量的类型, 不用它的值,那么可以不需要赋值:

    1. switch areaIntf.(type) {
    2. case *Square:
    3. // TODO
    4. case *Circle:
    5. // TODO
    6. ...
    7. default:
    8. // TODO
    9. }

    example:

    1. func classifier(items ...interface{}) {
    2. for i, x := range items {
    3. switch x.(type) {
    4. case bool:
    5. fmt.Printf("Param #%d is a bool\n", i)
    6. case float64:
    7. fmt.Printf("Param #%d is a float64\n", i)
    8. case int, int64:
    9. fmt.Printf("Param #%d is a int\n", i)
    10. case nil:
    11. fmt.Printf("Param #%d is a nil\n", i)
    12. case string:
    13. fmt.Printf("Param #%d is a string\n", i)
    14. default:
    15. fmt.Printf("Param #%d is unknown\n", i)
    16. }
    17. }
    18. }