如何确定一个变量是切片还是数组?

huangapple go评论82阅读模式
英文:

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")
		}
	}
}

huangapple
  • 本文由 发表于 2014年4月26日 07:49:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/23304854.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定