Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking types of slices in golang

Tags:

go

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

like image 441
prl900 Avatar asked Jun 15 '14 07:06

prl900


People also ask

How do I find my slice type in Golang?

If a type is slice, Elem() will return the underlying type: func main() { foo := []int{1,2,3} fmt. Println(reflect. TypeOf(foo).

How do you compare slices in Golang?

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.

How can I check if two slices are equal Golang?

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.


1 Answers

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.

like image 169
Not_a_Golfer Avatar answered Oct 11 '22 02:10

Not_a_Golfer