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
+12.4k Golang : Pass database connection to function called from another package and HTTP Handler
+10.7k Golang : Simple image viewer with Go-GTK
+18.5k Golang : Padding data for encryption and un-padding data for decryption
+7.2k Golang : How to handle file size larger than available memory panic issue
+39.7k Golang : Convert to io.ReadSeeker type
+5.1k Javascript : Shuffle or randomize array example
+9.4k Golang : Populate slice with sequential integers example
+21.8k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+19.7k Golang : Compare floating-point numbers
+8.7k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+41k Golang : How do I convert int to uint8?
+20k nginx: [emerg] unknown directive "passenger_enabled"