Golang help reflection to get values
I'm very new in Go. I was wondering how do I get value of mappings out of this using Reflection in Go.
type url_mappings struct{
mappings map[string]string
}
func init() {
var url url_mappings
url.mappings = map[string]string{
"ur开发者_Go百科l": "/",
"controller": "hello"}
Thanks
import "reflect"
v := reflect.ValueOf(url)
f0 := v.Field(0) // Can be replaced with v.FieldByName("mappings")
mappings := f0.Interface()
mappings
's type is interface{}, so you can't use it as a map.
To have the real mappings
that it's type is map[string]string
, you'll need to use some type assertion:
realMappings := mappings.(map[string]string)
println(realMappings["url"])
Because of the repeating map[string]string
, I would:
type mappings map[string]string
And then you can:
type url_mappings struct{
mappings // Same as: mappings mappings
}
精彩评论