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)
I'm familiar with the fact that, in Go, interfaces define functionality, rather than data. You put a set of methods into an interface, but you are unable to specify any fields that would be required on anything that implements that interface.
interface{} is the Go empty interface, a key concept. Every type implements it by definition. An interface is a type, so you can define for example: type Dog struct { Age interface{} }
Since the interface is a type just like a struct, we can create a variable of its type. In the above case, we can create a variable s of type interface Shape .
An interface in Go is a type defined using a set of method signatures. The interface defines the behavior for similar type of objects. An interface is declared using the type keyword, followed by the name of the interface and the keyword interface . Then, we specify a set of method signatures inside curly braces.
An interface variable can be used to store any value that conforms to the interface, and call methods that art 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:
Define your results
type at the top level, rather than within the method body.
Make SearchItemsByUser
directly return a value of the results
type instead of interface{}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With