如何从map[string]interface{}创建一个字符串映射?

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

How to create a map of strings from map[string]interface{}?

问题

新手地鼠在这里。
我想要填充这个结构体字段:

userData map[string]interface{}

数据如下:

ud := map[string]string{"userName": "noob"}

但是我得到了这个编译时错误:

无法将ud(类型为map[string]string)作为map[string]interface{}类型的字段值使用

我还尝试了:

ud := map[string]interface{}{"userName": "noob".(string)}

但是这会报错:

语法错误:意外的字符串文字

我该如何修复这个问题?

英文:

Noob gopher here.
I'd like to fill data into this struct field:

userData map[string]interface{}

The data is like:

ud := map[string]string{"userName": "noob"}

but I get this comple time error:

> cannot use ud (type map[string]string) as type map[string]interface {}
> in field value

I also tried:

ud := map[string]interface{"userName": "noob".(string)}

but this gives:

> syntax error: unexpected string literal

How can I fix this?

答案1

得分: 20

感谢gopher slack上的好心人,我意识到问题出在哪里了。
基本上,我只是错过了接口的{},像这样:

ud := map[string]interface{}{"userName": "noob"}
英文:

Thanks good guys on gopher slack, I realized what was wrong.
Basically I just missed {} of the interface, like this:

ud := map[string]interface{}{"userName": "noob"}

答案2

得分: 4

你也可以这样做:

ud := make(map[string]interface{})
ud["userName"] = "noob"
英文:

Also you can do like this

ud := make(map[string]interface{})
ud["userName"] = "noob"

huangapple
  • 本文由 发表于 2017年3月12日 09:40:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/42742766.html
匿名

发表评论

匿名网友

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

确定