英文:
How do you determine if a variable is a slice or array?
问题
我有一个函数,它接收一个映射(map),其中的每个元素需要根据它是原始类型还是切片类型进行不同的处理。切片的类型事先是未知的。我该如何确定哪些元素是切片(或数组),哪些不是?
英文:
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?
答案1
得分: 54
请看一下reflect
包。
这是一个可运行的示例,供您参考。
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, "是一个切片,元素类型为", rt.Elem())
case reflect.Array:
fmt.Println(k, "是一个数组,元素类型为", rt.Elem())
default:
fmt.Println(k, "是其他类型")
}
}
}
英文:
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")
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论