2014-06-15 07:39
浏览 155


I use the reflect package to check the type of my variables. For example if I want to check if var is an integer I do:

reflect.TypeOf(var).Kind == reflect.Int

How can I check if my variable is an int or float slice?

I can only see Slice as one of the types returned by Kind() but this slice could be of any type

图片转代码服务由CSDN问答提供 功能建议

我使用反射包检查变量的类型。 例如,如果我想检查var是否为整数,我会做:

  reflect.TypeOf(var).Kind == reflect.Int 



  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doufan3958 2014-06-15 07:47

    If a type is slice,Elem() will return the underlying type:

    func main() {
        foo := []int{1,2,3}
        fmt.Println(reflect.TypeOf(foo).Elem()) //prints "int"
        fmt.Println(reflect.TypeOf(foo).Elem().Kind() == reflect.Int) //true!

    You better check that it's a slice before, of course.

    点赞 打赏 评论

相关推荐 更多相似问题