您如何确定变量是切片还是数组?
问题描述:
I have a function that is passed a map, each element of which needs to be handled differently depending on whether it is a primitive or a slice. The type of the slice is not known ahead of time. How can I determine which elements are slices (or arrays) and which are not?
我有一个传递给映射的函数,根据其是否需要对每个元素进行不同的处理 原语或切片。 切片的类型事先未知。 如何确定哪些元素是切片(或数组)而哪些不是切片? p> div>
答
Have a look at the reflect
package.
Here is a working sample for you to play with.
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")
}
}
}