英文:
Golang help reflection to get values
问题
我在Go语言中非常新手。我想知道如何使用Go中的反射来获取映射的值。
type url_mappings struct{
mappings map[string]string
}
func init() {
var url url_mappings
url.mappings = map[string]string{
"url": "/",
"controller": "hello"}
谢谢
英文:
I'm very new in Go. I was wondering how do I get value of mappings out of this using Reflection in Go.
<pre>
<code>
type url_mappings struct{
mappings map[string]string
}
func init() {
var url url_mappings
url.mappings = map[string]string{
"url": "/",
"controller": "hello"}
</code>
</pre>
Thanks
答案1
得分: 5
import "reflect"
v := reflect.ValueOf(url)
f0 := v.Field(0) // 可以用 v.FieldByName("mappings") 替换
mappings := f0.Interface()
mappings
的类型是 interface{},所以你不能将其用作 map。
要获得真正的 mappings
,其类型为 map[string]string
,你需要使用一些 类型断言:
realMappings := mappings.(map[string]string)
println(realMappings["url"])
由于重复的 map[string]string
,我会这样做:
type mappings map[string]string
然后你可以:
type url_mappings struct{
mappings // 和:mappings mappings 一样
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论