Golang帮助反射获取值

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

Golang help reflection to get values

问题

我在Go语言中非常新手。我想知道如何使用Go中的反射来获取映射的值。

  1. type url_mappings struct{
  2. mappings map[string]string
  3. }
  4. func init() {
  5. var url url_mappings
  6. url.mappings = map[string]string{
  7. "url": "/",
  8. "controller": "hello"}
  9.  

谢谢

英文:

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 一样
}

英文:
  1. import &quot;reflect&quot;
  2. v := reflect.ValueOf(url)
  3. f0 := v.Field(0) // Can be replaced with v.FieldByName(&quot;mappings&quot;)
  4. 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:

  1. realMappings := mappings.(map[string]string)
  2. println(realMappings[&quot;url&quot;])

Because of the repeating map[string]string, I would:

  1. type mappings map[string]string

And then you can:

  1. type url_mappings struct{
  2. mappings // Same as: mappings mappings
  3. }

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:

确定