Search code examples
interfacego

golang how to access interface fields


I have a function as below which decodes some json data and returns it as an interface

package search

func SearchItemsByUser(r *http.Request) interface{} {

    type results struct {
        Hits             hits
        NbHits           int
        NbPages          int
        HitsPerPage      int
        ProcessingTimeMS int
        Query            string
        Params           string
    }

    var Result results

    er := json.Unmarshal(body, &Result)
    if er != nil {
        fmt.Println("error:", er)
    }
    return Result

}

I'm trying to access the data fields ( e.g. Params) but for some reasons it says that the interface has no such field. Any idea why ?

func test(w http.ResponseWriter, r *http.Request) {

    result := search.SearchItemsByUser(r)
        fmt.Fprintf(w, "%s", result.Params)

Solution

  • An interface variable can be used to store any value that conforms to the interface, and call methods that are part of that interface. Note that you won't be able to access fields on the underlying value through an interface variable.

    In this case, your SearchItemsByUser method returns an interface{} value (i.e. the empty interface), which can hold any value but doesn't provide any direct access to that value. You can extract the dynamic value held by the interface variable through a type assertion, like so:

    dynamic_value := interface_variable.(typename)
    

    Except that in this case, the type of the dynamic value is private to your SearchItemsByUser method. I would suggest making two changes to your code:

    1. Define your results type at the top level, rather than within the method body.

    2. Make SearchItemsByUser directly return a value of the results type instead of interface{}.