我有一个传递给map的函数,每个元素都需要根据它是基元还是切片来区别对待。切片的类型未提前知道。如何确定哪些元素是切片(或数组),哪些不是?
答案 0 :(得分:21)
查看reflect
包。
Here is a working sample让你玩。
package main
import "fmt"
import "reflect"
func main() {
m := make(map[string]interface{})
m["a"] = []string{"a", "b", "c"}
m["b"] = [4]int{1, 2, 3, 4}
test(m)
}
func test(m map[string]interface{}) {
for k, v := range m {
rt := reflect.TypeOf(v)
switch rt.Kind() {
case reflect.Slice:
fmt.Println(k, "is a slice with element type", rt.Elem())
case reflect.Array:
fmt.Println(k, "is an array with element type", rt.Elem())
default:
fmt.Println(k, "is something else entirely")
}
}
}