美文网首页Go
Go开发的各种坑 - 类型判断

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

作者: 红薯爱帅 | 来源:发表于2023-05-14 09:25 被阅读0次

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)
    }
}

相关文章

  • 五. Go(Go protobuf)

    gopath开发模式和go modules开发模式对比 goland创建项目时没用go mod模式选项的坑 在Go...

  • Go语言的类型系统概览

    本文将介绍go语言中的各种类型和go类型系统中的各种概念。 不知道这些概念,将很难理解go语言。 概念:基本类型 ...

  • golang系列教程

    Go包管理 Go开发工具 Go Doc 文档 Go 数组 Go 切片 Go Map Go 类型 Go 函数方法 G...

  • go判断interface类型及类型转换

    在golang中,interface{}允许接纳任意值,类似于Java中的Object类型。 可以直接用switc...

  • 常用的工具函数

    在前端开发中,往往我们需要使用各种工具函数 判断是数组类型 es6版本 早期版本 判断是对象 es6版本 判断NA...

  • BLE开发的各种坑

    这段时间在做低功耗蓝牙(BLE)应用的开发(并不涉及蓝牙协议栈)。总体感觉 Android BLE 还是不太稳定,...

  • 05-Go语言常量和变量-指趣学院

    Go语言数据类型 Go语言本质是用C语言编写的一套高级开发语言, 所以Go语言中的数据类型大部分都是由C语言演变而...

  • Mac Golang 开发环境配置

    Mac Golang 开发环境配置 Golang 介绍 Go(又称Golang)是Google开发的一种静态强类型...

  • 数据类型(二)

    前言:在JavaScript中,各种数据类型和情况下在“if”中的判断总结。 (1)基本类型判断 字符串类型 结论...

  • GO语言之类型断言

    概述 类型断言在GO中指的就是判断接口型变量运行时的实际类型.例如: 上面的例子中,变量f声明是接口类型,实际的类...

网友评论

    本文标题:Go开发的各种坑 - 类型判断

    本文链接:https://www.haomeiwen.com/subject/tzjjjdtx.html