开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜