vendredi 23 juin 2017

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

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





Aucun commentaire:

Enregistrer un commentaire