Home > Article > Backend Development > How should I use type mapinterface {} in golang
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?
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!