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
+7.9k Golang : Sort words with first uppercase letter
+17.5k Golang : [json: cannot unmarshal object into Go value of type]
+13.5k Generate salted password with OpenSSL example
+51.2k Golang : Check if item is in slice/array
+29.6k Golang : Get and Set User-Agent examples
+4.6k Golang : How to pass data between controllers with JSON Web Token
+5.8k Golang : Use NLP to get sentences for each paragraph example
+9.3k Golang : Qt Yes No and Quit message box example
+29.2k Golang : How to create new XML file ?
+10.1k Golang : Wait and sync.WaitGroup example
+23.4k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+8.3k Golang : Generate Datamatrix barcode