dpd46554
2017-11-26 12:14
浏览 411
已采纳

类型接口{}不支持golang中的索引编制

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?

图片转代码服务由CSDN问答提供 功能建议

我有这样的地图:

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

该映射应该包含从字符串到对象数组的映射。 数组可以具有不同的类型,例如 [] Users [] Hosts 。 我填充了该数组:

  TopologyMap [“ Users”] = Users_Array 
TopologyMap [“ Hosts”] = Hosts_Array 
   
 
  

但是当我尝试从中获取元素时:

  Map [“ Users”] [0] 
   
 \  n 

给出错误: (类型接口{}不支持索引)

我该如何克服? \ n

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dph6308 2017-11-26 12:20
    已采纳

    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

    打赏 评论
  • doushi6947 2017-11-26 13:15

    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
    ", 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.

    打赏 评论

相关推荐 更多相似问题