Go lang accessing {interface{} | []interface{}] 's index?

Issue

I have a little bit trouble with interfaces, ı can not share any code cause of this problem result of many lines of code. So here is the problem , I need to access this []interface{} elements, but it gives me an error like (interface{}) does not support indexing any help would be great. I’m stuck now.
enter image description here

Solution

you need a type switch to determine what is the interface underlying type.
See: https://go.dev/tour/methods/16

Example: (https://go.dev/play/p/gSRuHBoQYah):

package main

import (
        "encoding/json"
        "fmt"
        "log"
)

func printInterface(o interface{}) {
        switch v := o.(type) {
        case map[string]interface{}:
                fmt.Printf("this is a map. a: %+v\n", v["a"])
        case []interface{}:
                fmt.Printf("this is a slice, len: %d, v[0] is: %+v, type: %T\n", len(v), v[0], v[0])
        default:
                fmt.Printf("this is %T\n", v)

        }
}

func main() {
        var result1 interface{}
        listOfObjects := `[{"a":1}, {"a":2}]`
        if err := json.Unmarshal([]byte(listOfObjects), &result1); err != nil {
                log.Fatal(err)
        }

        printInterface(result1)

        var result2 interface{}
        singleObject := `{"a":1, "b":2}`
        if err := json.Unmarshal([]byte(singleObject), &result2); err != nil {
                log.Fatal(err)
        }

        printInterface(result2)
}

Answered By – serge-v

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.