func getLatestTxs() map[string]interface{}{} {
fmt.Println("hello")
resp, err := http.Get("http://api.etherscan.io/api?module=account&action=txlist&address=0x266ac31358d773af8278f625c4d4a35648953341&startblock=0&endblock=99999999&sort=asc&apikey=5UUVIZV5581ENPXKYWAUDGQTHI956A56MU")
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Errorf("etherscan访问失败")
}
ret := map[string]interface{}{}
json.Unmarshal(body, &ret)
if ret["status"] == 1 {
return ret["result"]
}
}
I want return map[string]interface{}{}
in my code.
but i got compile error syntax error: unexpected [ after top level declaration
if i change map[string]interface{}{}
to interface{}
, there is no compile error any more.
Attention i use map[string]interface{}{}
because i want return a map list.
The code map[string]interface{}{}
is a composite literal value for an empty map. Functions are declared with types, not values. It looks like you want to return the slice type []map[string]interface{}
. Use the following function:
func getLatestTxs() []map[string]interface{} {
fmt.Println("hello")
resp, err := http.Get("http://api.etherscan.io/api?module=account&action=txlist&address=0x266ac31358d773af8278f625c4d4a35648953341&startblock=0&endblock=99999999&sort=asc&apikey=5UUVIZV5581ENPXKYWAUDGQTHI956A56MU")
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Errorf("etherscan访问失败")
}
var ret struct {
Status string
Result []map[string]interface{}
}
json.Unmarshal(body, &ret)
if ret.Status == "1" {
return ret.Result
}
return nil
}
Create return type to map[string]interface{}
. Because the response returned from GET
request is of type map[string]interface{}
not map[string]interface{}{}
which is a composite literal. So you can use it like
func getLatestTxs() map[string]interface{} {
fmt.Println("hello")
// function body code ....
return ret
}
For this line
if i change map[string]interface{}{} to interface{}, there is no compile error any more.
We can convert anything to interface{}
because it works as a wrapper which can wrap any type and will save the underlying type and its value. The value can be received using type assertion for an underlying type. So in your case when you are using an interface it will wrap map[string]interface{}
value. For fetching the value it is required to type assert as below.
func getLatestTxs() interface{} {
fmt.Println("hello")
// function code .....
//fmt.Println(ret["result"])
return ret
}
ret["result"].(interface{}).([]interface{})
print the underlying map[string]interface{}
to get the value of single object inside result
fmt.Println(ret["result"].(interface{}).([]interface{})[0].(map[string]interface{})["from"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With