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
+4.9k HTTP common errors and their meaning explained
+5.6k Unix/Linux : How to find out the hard disk size?
+40.1k Golang : UDP client server read write example
+5.6k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+10.5k Swift : Convert (cast) String to Integer
+6.3k Golang : Selection sort example
+16.7k Golang : Gzip file example
+8.8k Golang : Random integer with rand.Seed() within a given range
+10.9k Golang : Removes punctuation or defined delimiter from the user's input
+34.1k Golang : Create x509 certificate, private and public keys
+8.2k Golang : Reverse text lines or flip line order example