go - golang函数可以返回接口{}{} - 如何返回地图列表
问题描述
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"]
}
}
我想map[string]interface{}{}
在我的代码中返回。
但我得到了编译错误syntax error: unexpected [ after top level declaration
如果我更改map[string]interface{}{}
为interface{}
,则不再有编译错误。
注意我使用map[string]interface{}{}
,因为我想返回一个地图列表。
解决方案
该代码map[string]interface{}{}
是空地图的复合文字值。函数是用类型声明的,而不是值。看起来您想返回切片类型[]map[string]interface{}
。使用以下功能:
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
}
推荐阅读
- mysql - 使用从同一表中的另一行中减去的值更新 MySQL 日期时间列
- javascript - FORCE HttpRequest 在没有打开 Chrome 开发工具的情况下禁用缓存
- node.js - 不适用于“package.json”中的“type”:“module”
- python - 带有 nginx 反向代理的 django SECURE_SSL_REDIRECT
- ios - 隐藏/显示输入附件视图
- amazon-web-services - AWS S3 存储桶中的复制作为数据备份
- mysql - 以短词开头的 MySQL 全文搜索失败
- java - 三重 DES 解密:ECB 模式不能使用 IV
- c - 如何通过引用 ac 函数`sscanf()` 来传递变量
- android - 我可以在 Graphview Android 中保存多少数据