How should I use type mapinterface {} in golang

王林
Release: 2024-02-05 23:06:12
forward
1101 people have browsed it

我应该如何在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"]))
Copy after login

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"]))
Copy after login

This will result in a compiler error:

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

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"]))
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!