type interface {} does not support indexing in golang

房东的猫 提交于 2020-06-14 07:16:56

问题


I have such map:

Map := make(map[string]interface{})

This map is supposed to contain mapping from string to array of objects. Arrays can be of different types, like []Users or []Hosts. I populated this array:

TopologyMap["Users"] = Users_Array
TopologyMap["Hosts"] = Hosts_Array

but when I try to get an elements from it:

Map["Users"][0]

it gives an error: (type interface {} does not support indexing)

How can I overcome it?


回答1:


You have to explicitly convert your interface{} to a slice of the expected type to achieve it. Something like this https://play.golang.org/p/yZmniZwFar




回答2:


First thing to be noted is the interface{} can hold any data type including function and struct or []struct. Since the error gives you :

(type interface {} does not support indexing)

It means that it holds no slice or no array values. Because you directly call the index in this case is 0 to an interface{} and you assume that the Map["Users"] is an array. But it is not. This is one of very good thing about Go it is statically type which mean all the data type is check at compiled time.

if you want to be avoid the parsing error like this:

panic: interface conversion: interface {} is []main.User, not []main.Host

To avoid that error while your parsing it to another type like Map["user"].([]User) just in case that another data type pass to the interface{} consider the code snippet below :

u, ok := myMap["user"].([]User)
if ok {
    log.Printf("value = %+v\n", u)
}

Above code is simple and you can use it to check if the interface match to the type you are parsing.

And if you want to be more general passing the value to your interface{} at runtime you can check it first using reflect.TypeOf() please consider this code :

switch reflect.TypeOf(myMap["user"]).String() {
case "[]main.User":
    log.Println("map = ", "slice of user")
    logger.Debug("map = ", myMap["user"].([]User)[0])

case "[]main.Host":
    log.Println("map = ", "slice of host")
    logger.Debug("map = ", myMap["user"].([]Host)[0])

}

after you know what's the value of the interface{} you can confidently parse it the your specific data type in this case slice of user []User. Not that the main there is a package name you can change it to yours.



来源:https://stackoverflow.com/questions/47496040/type-interface-does-not-support-indexing-in-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!