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
+5.2k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+9.1k Golang : Build and compile multiple source files
+7.9k Swift : Convert (cast) String to Double
+27.8k PHP : Convert(cast) string to bigInt
+9.8k Golang : Detect number of active displays and the display's resolution
+12k Golang : Determine if time variables have same calendar day
+10.9k Golang : Command line file upload program to server example
+21.4k Golang : Create and resolve(read) symbolic links
+21.3k Golang : Clean up null characters from input data
+29.9k Golang : Record voice(audio) from microphone to .WAV file
+22.1k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."