golang reflect笔记

栏目: Go · 发布时间: 7年前

内容简介:最近有大量用到reflect,给一流开源项目gin贡献的pr就是这方面的技巧,也在自己的开源项目中使用了大量使用reflect简化接口开发。鉴于reflect的接口特别难用,特别容易忘记,记录下。

最近有大量用到reflect,给一流开源项目gin贡献的pr就是这方面的技巧,也在自己的开源项目中使用了大量使用reflect简化接口开发。鉴于reflect的接口特别难用,特别容易忘记,记录下。

判断类型

// 提取类型信息到变量里
var stringSliceType = reflect.TypeOf([]string{})
var intSliceType = reflect.TypeOf([]int{})
var int32SliceType = reflect.TypeOf([]int32{})

func typeCheck(x interface{}) {
    // 提取interface{}里面的类型信息
    vt := reflect.ValueOf(x).Type()
    switch vt {
    case stringSliceType:
        fmt.Printf("[]string{}\n")
    case intSliceType:
        fmt.Printf("[]int{}\n")
    case int32SliceType:
        fmt.Printf("[]int32{}\n")
    default:
        fmt.Printf("unkown type\n")
    }   
}

func main() {
    typeCheck([]string{})
    typeCheck([]int{})
    typeCheck([]int32{})
    typeCheck(0)
}
// 输出
// []string{}
// []int{}
// []int32{}
// unkown type

判断指针类型和空指针

func checkPtrAndNil(x interface{}) {
    v := reflect.ValueOf(x)
    if v.Kind() == reflect.Ptr {
        fmt.Printf("%v is pointer\n", v.Type())
        if v.IsNil() {
            fmt.Printf("%v is is a null pointer\n", v.Type())
            return
        }

    }   

    fmt.Printf("%v is value\n", v.Type())
}

func main() {
    var ip *int
    var sp *string
    var i32p *int32

    checkPtrAndNil(ip)
    checkPtrAndNil(sp)
    checkPtrAndNil(i32p)
    checkPtrAndNil(3)
}

// 输出
// *int is pointer
// *int is is a null pointer
// *string is pointer
// *string is is a null pointer
// *int32 is pointer
// *int32 is is a null pointer
// int is value

以上所述就是小编给大家介绍的《golang reflect笔记》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

How to Think About Algorithms

How to Think About Algorithms

Jeff Edmonds / Cambridge University Press / 2008-05-19 / USD 38.99

HOW TO THINK ABOUT ALGORITHMS There are many algorithm texts that provide lots of well-polished code and proofs of correctness. Instead, this one presents insights, notations, and analogies t......一起来看看 《How to Think About Algorithms》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具