can golang function return interface{}{} - how to return a map list

眭文峰 picture 眭文峰 · Apr 25, 2018 · Viewed 9.1k times · Source
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.

Answer

Bayta Darell picture Bayta Darell · Apr 25, 2018

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
}