golang check length of a slice if it is a slice map[string]interface{}

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

golang check length of a slice if it is a slice map[string]interface{}

问题

我想查看v的类型是否为slice。如果是的话,我希望检查它的长度。

var a = make(map[string]interface{})

a["a"] = 1
a["b"] = []string{"abc", "def"}
a["c"] = []int{1,2,3}

for k, v := range a {
    if reflect.TypeOf(v).Kind() == reflect.Slice {
        t.Log("Length of map", k, len(v)) // invalid argument v (type interface {}) for len
    }
}

现在我知道它是一个slice,我该如何检查它的长度?

期望的输出:

Length of map b 2
Length of map c 3
英文:

I want to see if the type of v is a slice. If so, I wish to check the length of it.

var a = make(map[string]interface{})

a["a"] = 1
a["b"] = []string{"abc", "def"}
a["c"] = []int{1,2,3}

for k, v := range a {
	if reflect.TypeOf(v).Kind() == reflect.Slice {
		t.Log("Length of map", k, len(v)) // invalid argument v (type interface {}) for len
    }
}

How do I check the length of my slice, now that I know it is a slice?

Expected output:

Length of map b 2
Length of map c 3

答案1

得分: 4

v仍然是一个interface{}类型,你不能对其应用len()函数。你可以使用反射来获取长度,使用reflect.ValueOf(v).Len()

英文:

v is still a interface{}, which you cannot apply len() to. You can use reflection to get the length with reflect.ValueOf(v).Len().

huangapple
  • 本文由 发表于 2017年6月23日 22:07:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/44723460.html
匿名

发表评论

匿名网友

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

确定