Reputation: 4179
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
Upvotes: 7
Views: 6717
Reputation: 49195
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.
Upvotes: 9