首页 > 解决方案 > 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{}{},因为我想返回一个地图列表。

标签: gointerfacego-map

解决方案


该代码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
}

推荐阅读