Home >Backend Development >Golang >How to Fix 'type interface {} Does Not Support Indexing' in Go Maps?

How to Fix 'type interface {} Does Not Support Indexing' in Go Maps?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 10:18:17691browse

How to Fix

How to Index a Map Containing an Array of Objects in Go: Resolving "Type Interface {} Does Not Support Indexing" Error

Indexing a map containing an array of objects in Go can lead to the error "type interface {} does not support indexing." This error occurs because Go doesn't know the expected type of the array elements, which are represented by the interface type.

To overcome this error and retrieve the desired element, you need to explicitly convert the interface{} value to the specific type you expect.

Consider the following map:

Map := make(map[string]interface{})
Map["Users"] = Users_Array
Map["Hosts"] = Hosts_Array

To access the first element of the "Users" array, use the following code:

Users_Array := Map["Users"].([]User)
firstUser := Users_Array[0]

Similarly, for the "Hosts" array:

Hosts_Array := Map["Hosts"].([]Host)
firstHost := Hosts_Array[0]

This conversion to the specific type ensures that the indexing operation can be performed successfully. Failure to perform the conversion will result in the "type interface {} does not support indexing" error.

Here's an example demonstrating the conversion and indexing process:

package main

import "fmt"

type Host struct {
    Name string
}

type User struct {
    Name string
}

func main() {
    Map := make(map[string]interface{})
    Map["hosts"] = []Host{{"test.com"}, {"test2.com"}}
    Map["users"] = []User{{"john"}, {"jane"}}

    hm := Map["hosts"].([]Host)
    fmt.Println(hm[0])

    um := Map["users"].([]User)
    fmt.Println(um[0])
}

The above is the detailed content of How to Fix 'type interface {} Does Not Support Indexing' in Go Maps?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn