2011-07-05 38 views
1

我在Go中很新。我想知道如何通过使用Reflection中的Go来获得映射的价值。Golang帮助反思获得价值

 

type url_mappings struct{ 
    mappings map[string]string 
} 

func init() { 
    var url url_mappings 
    url.mappings = map[string]string{ 
     "url": "/", 
     "controller": "hello"} 
 

感谢

+1

为什么要使用反射?你想解决什么问题? – peterSO

+0

我试图让用户有自己的映射,我将使用反射循环来检查所有模式。像Grails中的URL_Mappings一样。 :) – toy

+0

@toy:我仍然不明白为什么反射是必要的 – newacct

回答

5
import "reflect" 
v := reflect.ValueOf(url) 
f0 := v.Field(0) // Can be replaced with v.FieldByName("mappings") 
mappings := f0.Interface() 

mappings的类型是接口{},所以你不能把它作为一个地图。 要具有真正的mappings,它的类型是map[string]string,你需要使用一些type assertion

realMappings := mappings.(map[string]string) 
println(realMappings["url"]) 

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

type mappings map[string]string 

然后你可以:

type url_mappings struct{ 
    mappings // Same as: mappings mappings 
} 
+0

我运行这个时遇到了这个错误。 – toy

+0

testing:panic:reflect:调用reflect.Value·ptr上的字段值 – toy

+2

这是因为您将指针传递给'url'而不是'url'本身。如果你坚持传递一个指针,用这个改变*第2行*:v:= reflect.ValueOf(url).Elem()'。 –