Golang : Fix type interface{} has no field or no methods and type assertions example
For new comers to Golang exploring interface{}
for the first time or if you ever use interface{} to handle some arbitrary data, chances are that you will see this error message :
type interface {} has no field or method
or
type interface {} is interface with no methods
To fix this problem, you will need to convert the interface{} to a suitable type or extract the value(variable) with the explicit(correct)type from the interface{} with type assertions.
For example :
// convert the json objects from interface{} to []interface{}
// [] = slice/array type
var jsonObjs interface{}
json.Unmarshal([]byte(jsonStr), &jsonObjs)
objSlice, ok := jsonObjs.([]interface{})
or
// convert invoices to map[string]interface{}
for index, value := range invoices.(map[string]interface{}) {
fmt.Println(index, value)
}
Hope this helps!
References :
https://www.socketloop.com/tutorials/golang-count-json-objects-and-convert-to-slice-array
See also : Golang : Count JSON objects and convert to slice/array
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+18.2k Golang : Measure http.Get() execution time
+11.1k Golang : Display list of countries and ISO codes
+12.8k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+10k How to test Facebook App on localhost ?
+4.9k Golang : Find change in a combination of coins example
+7.6k Golang : Set or add headers for many or different handlers
+3.9k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+7.5k Golang : How to join strings?
+12.7k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+16.5k Golang : How to log each HTTP request to your web server?
+30.1k Golang : Math pow(the power of x^y) example
+6.3k Golang : Scanf function weird error in Windows