toy
toy

Reputation: 12141

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{
        "url": "/",
        "controller": "hello"}

Thanks

Upvotes: 1

Views: 4215

Answers (1)

Zippo
Zippo

Reputation: 16420

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
}

Upvotes: 5

Related Questions