内容简介:最近有大量用到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笔记》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 【每日笔记】【Go学习笔记】2019-01-04 Codis笔记
- 【每日笔记】【Go学习笔记】2019-01-02 Codis笔记
- 【每日笔记】【Go学习笔记】2019-01-07 Codis笔记
- vue笔记3,计算笔记
- Mysql Java 驱动代码阅读笔记及 JDBC 规范笔记
- 【每日笔记】【Go学习笔记】2019-01-16 go网络编程
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The CS Detective: An Algorithmic Tale of Crime, Conspiracy, and
Jeremy Kubica / No Starch Press / 2016-8-15 / USD 13.74
Meet Frank Runtime. Disgraced ex-detective. Hard-boiled private eye. Search expert.When a robbery hits police headquarters, it's up to Frank Runtime and his extensive search skills to catch the culpri......一起来看看 《The CS Detective: An Algorithmic Tale of Crime, Conspiracy, and 》 这本书的介绍吧!