Golang帮助反射获取值

huangapple go评论142阅读模式
英文:

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 &quot;reflect&quot;
v := reflect.ValueOf(url)
f0 := v.Field(0) // Can be replaced with v.FieldByName(&quot;mappings&quot;)
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[&quot;url&quot;])

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
}

huangapple
  • 本文由 发表于 2011年7月5日 19:00:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/6581575.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定