Checking slice types in golang

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

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

How to check if my variable is part of int or float?

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

+4
source share
1 answer

If the type is a slice, Elem()returns the base 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 this is a snippet before, of course.

+6
source

Source: https://habr.com/ru/post/1544627/


All Articles