在一个变量中返回多个地图

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

Returning multiple maps in one variable

问题

我正在处理一个XML解析器,并且我遇到了以下问题:

我有一个函数,用于获取一些标签的值,例如电影标题和发布日期:

func whatever() map[string]interface{} {

}

我希望它返回以下形式的内容:

[map[title:Movie01] map[title:Movie02]]

但是不能改变返回类型。

目前我只有:

map[title:Movie01]

显然,我不能在一个单独的map中有重复的"title"键。

你能帮我解决这个问题吗?这个问题困扰了我几个小时了。

英文:

I am working on a XML parser and I have the following problem :

I have this function which gather some tags value, for example movie title and release date :

func whatever() map[string]interface{} {

}

And I would like it to return something of this form :

[map[title:Movie01] map[title:Movie02]]

Without changing the return type.

All I have for now is :

map[title:Movie01]

And obviously I cannot have duplicate "title" key in one single map.

Can you help me on this ? It's been bothering me for a couple of hours now.

答案1

得分: 1

根据记录,正如我在评论中提到的,你可以尝试返回一个切片的映射,例如:

func whatever() []map[string]interface{} {
}

不过,根据你的数据,你可能会发现为你的领域定义一个合适的结构体并返回它会有更好的解决方案。

英文:

For the record then, as I mentioned in the comments you could try returning a slice of maps such as

func whatever() []map[string]interface{} {
}

Though depending on your data you might find a better solution in defining an appropriate struct for your domain and returning that.

huangapple
  • 本文由 发表于 2015年2月7日 03:32:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/28373369.html
匿名

发表评论

匿名网友

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

确定