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
If a type is slice, Elem() will return the underlying type: func main() { foo := []int{1,2,3} fmt. Println(reflect. TypeOf(foo).
Golang slice allows us to compare two slices of the byte type with each other using bytes. Compare() function. The Compare() function returns an integer value which represents that these slices are equal or not and the values are: If the result is 0, then sliceA == sliceB.
To check if two slices are equal, write a custom function that compares their lengths and corresponding elements in a loop. You can also use the reflect. DeepEqual() function that compares two values recursively, which means it traverses and checks the equality of the corresponding data values at each level.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With