Skip to content

Instantly share code, notes, and snippets.

@millukii
Forked from VojtechVitek/map-type-reflect.go
Created December 27, 2019 18:31
Show Gist options
  • Select an option

  • Save millukii/b0b48eab82f0992ec13a2085d9b6f060 to your computer and use it in GitHub Desktop.

Select an option

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
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