-
-
Save millukii/b0b48eab82f0992ec13a2085d9b6f060 to your computer and use it in GitHub Desktop.
Golang - How to get an underlying type of a map using reflect pkg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "reflect" | |
| ) | |
| type Map map[string]string | |
| type Object struct { | |
| Items Map | |
| } | |
| func main() { | |
| obj := &Object{} | |
| t := reflect.ValueOf(obj).Elem().FieldByName("Items").Type() | |
| // The below gives me 'main.Map' type. But I want to get the | |
| // underlying type of 'map[string]string'... How? | |
| fmt.Printf("From:\t%v\n", t) | |
| fmt.Println("I want:\tmap[string]string") | |
| // Reflection again.. | |
| if (t.Kind() == reflect.Map) { | |
| fmt.Printf("Got:\t%v", reflect.MapOf(t.Key(), t.Elem())) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment