2011-07-05 42 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()'。 –