Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type interface {} does not support indexing in golang

Tags:

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?

like image 488
Kenenbek Arzymatov Avatar asked Nov 26 '17 12:11

Kenenbek Arzymatov


Video Answer


1 Answers

You have to explicitly convert your interface{} to a slice of the expected type to achieve it. Something like this:

package main
    
import "fmt"
    
type Host struct {
    Name string
}

func main() {
    Map := make(map[string]interface{})
    Map["hosts"] = []Host{Host{"test.com"}, Host{"test2.com"}}
    
    hm := Map["hosts"].([]Host)
    fmt.Println(hm[0])
}

Playground link

like image 168
Vadyus Avatar answered Sep 18 '22 19:09

Vadyus