dongrandi8411 2018-04-25 04:29
浏览 110
已采纳

可以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"]
    }
}

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.

  • 写回答

2条回答 默认 最新

  • doufen3786 2018-04-25 04:38
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?