且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

golang无效操作:type interface {}不支持索引

更新时间:2021-12-28 17:36:18

d 的类型是 interface {} ,所以你不能像 d [ data] ,你需要另一个类型断言:

d is of type interface{}, so you cannot index it like d["data"], you need another type assertion:

test := d.(map[string]interface{})["data"].(map[string]interface{})["type"]
fmt.Println(test)

然后它就会工作。输出将是。请参阅 Go Playground 上的实例。

Then it will work. Output will be "domains". See a working example on the Go Playground.

还要注意,如果你声明 d 的类型为 map [string] interface {} ,那么你可以省去第一个类型断言:

Also note that if you declare d to be of type map[string]interface{}, you can spare the first type assertion:

var d map[string]interface{}
if err := json.NewDecoder(response.Body).Decode(&d); err != nil {
    panic(err)
}
test := d["data"].(map[string]interface{})["type"]
fmt.Println(test)

输出是一样的。试试去游乐场

如果您需要多次执行这些操作和类似的操作,您可能会发现我的 github.com/icza/dyno 库有用(其主要目标是帮助使用动态对象)。

If you need to do these and similar operations many times, you may find my github.com/icza/dyno library useful (whose primary goal is to aid working with dynamic objects).