Go开发的各种坑 - 类型判断

1. 概述

Golang中,关于类型的判断,有几种方法

前两种方法的原理一致,实现的功能也相似,都不能解决类型别名的问题,因为类型别名是一种新的数据类型。
如果要解决类型别名的问题,需要通过reflect做类型判断。
本文通过一些代码来测试和验证。

2. 类型选择

在进行类型选择类型断言时,我们要很清楚我们要处理的数据的类型,只有这样才能得到数据的值。
注意:类型别名,是一种新的类型。

package main

import "fmt"

type myStr string
type aliasSlice0 []any
type aliasSlice1 []any

func test00(data any) {
    switch value := data.(type) {
    case []any:
        fmt.Println("type: []any", value)
    case []string:
        fmt.Println("type: []string", value)
    case aliasSlice0:
        fmt.Println("type: aliasSlice0", value)
    case myStr:
        fmt.Println("type: myStr", value)
    case string:
        fmt.Println("type: string", value)
    default:
        fmt.Println("default", value)
    }
}

func main() {
    test00(myStr("ddd"))
    test00("xxx")
    test00([]any{"aaa", "ccc"})
    test00([]string{"aaa", "ccc"})
    test00(aliasSlice0{"aaa", "ccc"})
    test00(aliasSlice1{"aaa", "ccc"})
}

  • 运行结果
type: myStr ddd
type: string xxx
type: []any [aaa ccc]
type: []string [aaa ccc]
type: aliasSlice0 [aaa ccc]
default [aaa ccc]

3. Reflect反射

通过反射,可以解决类型别名的问题,也可以很灵活地完成数据的处理。
只是操作比较麻烦,且处理时要考虑各种异常情况,不然,很容易出现bug。
有时间,可以基于reflect做一个package,做些事情,还是挺有意思的。

package main

import (
    "fmt"
    "reflect"
)

type aliasStr string

type skyObject interface {
    fly()
}

type Bird struct {
    name string
}

func (b *Bird) fly() {
    fmt.Println(b.name + "is flying")
}

func test01(data any) {
    typ := reflect.TypeOf(data).Kind()

    switch typ {
    case reflect.Map:
        iterMap := reflect.ValueOf(data).MapRange()
        for iterMap.Next() {
            if iterMap.Key().Kind() != reflect.String {
                fmt.Println("error ... key type != string")
                continue
            }
            switch iterMap.Value().Kind() {
            case reflect.Interface:
                if iterMap.Value().NumMethod() == 0 {
                    fmt.Println("map[string]any", data)
                } else {
                    fmt.Println("map[string]interface{...}", data)
                }
            case reflect.String:
                fmt.Println("map[string]string", data)
            case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
                fmt.Println("map[string]int", data)
            case reflect.Bool:
                fmt.Println("map[string]bool", data)
            case reflect.Slice, reflect.Array:
            case reflect.Struct:
            case reflect.Map:
            default:
                fmt.Println("default", data)
            }
        }
    case reflect.String:
        fmt.Println("Type: string", data)
    }
}

func main() {
    fmt.Println("=== Test === string")
    test01(aliasStr("aaa"))
    test01("bbb")

    fmt.Println("=== Test === map[string]string")
    test01(map[string]string{"aaa": "a1", "ccc": "c1"})

    fmt.Println("=== Test === map[string]any")
    test01(map[string]any{"aaa": "a1", "ccc": "c1"})

    fmt.Println("=== Test === map[string]skyObject")
    data := map[string]skyObject{
        "aaa": &Bird{name: "yanzi"},
        "ccc": &Bird{name: "laoying"},
    }
    test01(data)
}
  • 运行结果
=== Test === string
Type: string aaa
Type: string bbb
=== Test === map[string]string
map[string]string map[aaa:a1 ccc:c1]
map[string]string map[aaa:a1 ccc:c1]
=== Test === map[string]any
map[string]any map[aaa:a1 ccc:c1]
map[string]any map[aaa:a1 ccc:c1]
=== Test === map[string]skyObject
map[string]interface{...} map[aaa:0x1400010c1c0 ccc:0x1400010c1d0]
map[string]interface{...} map[aaa:0x1400010c1c0 ccc:0x1400010c1d0]

4. 后记

上述问题,是我在尝试遍历一个any类型的数据时遇到的。当然,该数据有一些限制,比如

  • map的key是string类型,value不限制类型
  • 数据中不存在struct、chan、pointer等特殊类型
  • 数据中可能存在slice

通过Type Switches方式遍历时,发现居然存在primitive.A类型,这是mongo driver的一个类型。

// From: go.mongodb.org/mongo-driver/bson/primitive
type A []interface{}

并且,我通过[]any没办法case到,所以深入分析了一下原因,并尝试通过reflect一劳永逸。
不过,最后我还是采用Type Switches方法完成整个数据的遍历,因为reflect太麻烦。

另外,Switche-Case的语法,如果case多个类型时,value还会处理成any类型。例如下面的代码,会报错cannot use value (variable of type any) as string value in argument to p: need type assertion

func main() {
    type myStr string

    var p = func(s string) {
        print(s)
    }

    var data any
    data = "hello world"
    switch value := data.(type) {
    case myStr, string:
        p(value)
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容