I'm have some confusion over golang reflect behaviour.
So basically I have a slice named src
with type []interface{}
. I would like to get the actual type of each element. This is what I did:
src := []interface{}{"noval", 0, nil}
srcType := reflect.ValueOf(src)
for i := 0; i < srcType.Len(); i++ {
each := srcType.Index(i)
if each.Interface() == nil {
fmt.Println("value", each.Interface(), "is nil")
} else {
switch each.Kind() {
case reflect.String:
fmt.Println("value", each.Interface(), "is string")
case reflect.Int, reflect.Int16:
fmt.Println("value", each.Interface(), "is int")
default:
fmt.Println("value", each.Interface(), "is ?")
}
}
}
Output:
value noval is ?
value 0 is ?
value <nil> is nil
I don't understand why type of elements "noval"
is not detected as string
, instead the default
is called from the switch
.
Also the 0
value should be identified as reflect.Int
but the default
is called again.
Can somebody enlighten me please, thank you in advance.
Aucun commentaire:
Enregistrer un commentaire