代码之家  ›  专栏  ›  技术社区  ›  user1050619

项列表的Golang类型断言

  •  0
  • user1050619  · 技术社区  · 6 年前

    例如:-

    result= {'outputs':[{'state':'md','country':'us'}, {'state':'ny','country':'ny'}]}
    

    上面的数据是用python表示的数据。

    在Golang中,相同的API返回数据,但当我尝试以结果[“outputs”]的形式访问数据时[0]

    获取此错误:-

    invalid operation: result["outputs"][0] (type interface {} does not support indexing)
    

    看起来我需要做一个类型转换,我应该用什么来进行类型转换, 我试过这个

    result["outputs"][0].(List)
    result["outputs"][0].([])
    

    但都给了我一个错误。

    我的类型转换应该是什么?

    1 回复  |  直到 6 年前
        1
  •  0
  •   icza    6 年前

    你写的值的类型是 []interface{} ,然后执行 type assertion

    还要注意,首先必须键入assert,然后再键入index,例如:

    outputs := result["outputs"].([]interface{})
    
    firstOutput := outputs[0]
    

    firstOutput 又会是 interface{} . 要访问其内容,您将需要另一个类型断言,很可能是 map[string]interface{} map[interface{}]interface{} .

    如果可以的话,用结构对数据建模,这样就不必做这种“类型断言废话”。

    还要注意,在动态对象(如您的对象)中,有一些第三方lib支持简单的“导航”。首先,有 github.com/icza/dyno (披露:我是作者)。

    dyno

    firstOutput, err := dyno.Get(result, "outputs", 0)
    

    要获得第一个输出的国家:

    country, err := dyno.Get(result, "outputs", 0, "country")
    

    您还可以“重用”以前查找的值,如下所示:

    firstOutput, err := dyno.Get(result, "outputs", 0)
    // check error
    country, err := dyno.Get(firstOutput, "country")
    // check error
    
    推荐文章