Golang帮助反思获得价值

toy*_*toy 1 reflection go

我是Go的新人.我想知道如何使用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"}

谢谢

Mos*_*vah 5

import "reflect"
v := reflect.ValueOf(url)
f0 := v.Field(0) // Can be replaced with v.FieldByName("mappings")
mappings := f0.Interface()
Run Code Online (Sandbox Code Playgroud)

mappings的类型是接口{},因此您不能将其用作地图.为了得到mappings它的类型map[string]string,你需要使用一些类型的断言:

realMappings := mappings.(map[string]string)
println(realMappings["url"])
Run Code Online (Sandbox Code Playgroud)

由于重复map[string]string,我会:

type mappings map[string]string
Run Code Online (Sandbox Code Playgroud)

然后你可以:

type url_mappings struct{
    mappings // Same as: mappings mappings
}
Run Code Online (Sandbox Code Playgroud)

  • 那是因为您将指针传递给`url`而不是`url`本身.如果你坚持传递一个指针,那么用这个改变*line 2*:`v:= reflect.ValueOf(url).Elem()`. (2认同)