从空接口中检索一个值

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

Retrieving a value from an empty interface

问题

我有一个空接口,我已经解析了一些 JSON 数据到这个接口中。

type Event interface {
}

目前,唯一的值是 name,并且已经正确设置了。然而,我无法弄清楚如何实际获取这个变量的值。我该如何做到这一点?

英文:

I have an empty interface to which I have parsed some json data.

type Event interface {
}

As of now, the only value is name, and this is being set correctly. However, I cannot figure how to actually retrieve the value of this variable. How do I do that?

答案1

得分: 5

如果你使用以下代码对JSON进行解组:

var f interface{}
err := json.Unmarshal(b, &f)

你可以使用类型断言来访问f的底层map[string]interface{}

m := f.(map[string]interface{})

详细信息请阅读这篇博客文章。

在<kbd><a href="http://play.golang.org/p/Y9a5rvnRxJ"> Go Playground</a></kbd>上尝试一下。

英文:

If you did something this to unmarshel the json

var f interface{}
err := json.Unmarshal(b, &amp;f)

You can use a type assertion to access f's underlying map[string]interface{}:

m := f.(map[string]interface{})

For more detail read this blog post.

Try It on <kbd><a href="http://play.golang.org/p/Y9a5rvnRxJ"> Go Playground</a></kbd>

huangapple
  • 本文由 发表于 2015年11月23日 04:16:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/33859665.html
匿名

发表评论

匿名网友

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

确定