How to check if a type is an array, slice, or map using reflection in Golang?

You can use reflection in Golang to check if a type is an array, slice, or map using the reflect package. Here's an example of how to do it:

package main import ( "fmt" "reflect" ) func main() { // Example types arr := [3]int{1, 2, 3} slice := []int{1, 2, 3} mp := map[string]int{"foo": 1, "bar": 2} // Checking types fmt.Printf("Is array? %t\n", isArray(arr)) fmt.Printf("Is slice? %t\n", isSlice(slice)) fmt.Printf("Is map? %t\n", isMap(mp)) } // Function to check if a type is an array func isArray(val interface{}) bool { v := reflect.ValueOf(val) return v.Kind() == reflect.Array } // Function to check if a type is a slice func isSlice(val interface{}) bool { v := reflect.ValueOf(val) return v.Kind() == reflect.Slice } // Function to check if a type is a map func isMap(val interface{}) bool { v := reflect.ValueOf(val) return v.Kind() == reflect.Map }

Output:

Is array? true Is slice? true Is map? true

In the above code, we define three types (an array arr, a slice slice, and a map mp). We then use the reflect package to get the reflect.Value of each type and compare its Kind with the relevant reflect kind (reflect.Array, reflect.Slice, reflect.Map) to determine if it is an array, slice, or map respectively.