Home  >  Article  >  Backend Development  >  How should I use type mapinterface {} in golang

How should I use type mapinterface {} in golang

王林
王林forward
2024-02-05 23:06:121104browse

我应该如何在golang中使用类型mapinterface {}

Question content

I am trying to retrieve data from the api. When I get data from api:

result, _ := s.getcases() // get cases via api
fmt.println(reflect.typeof(result.records[0]["cases"]))

It shows the type of result. records[0]["cases"] is map[string]interface {}

But, obviously I can't use this directly as a map. since:

fmt.println(reflect.typeof(result.records[0]["cases"]["id"]))

This will result in a compiler error:

invalid operation: cannot index result.Records[0]["Cases"] (map index
expression of type interface{})

May I know how to use this type in golang?


Correct answer


The value is of type interface{}, and according to the output of reflection, there is a map in the interface [string]interface{} value. Therefore, you must use type assertions to get the actual value stored in the interface:

fmt.Println(reflect.TypeOf(result.Records[0]["Cases"].(map[string]interface{})["Id"]))

The above is the detailed content of How should I use type mapinterface {} in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete