无法在地图中增加struct的值

时间:2016-07-10 16:14:15

标签: dictionary go struct

我有这样的结构

type EPMEmote struct {
    EmoteID   string
    EmoteCode string
    EPM       int64
} 

在此地图内

map[string]EPMEmote

我可以像这样轻松添加内容:

bot.epm[pmsg.Emotes[0].Name] = EPMEmote{
            EmoteCode: pmsg.Emotes[0].Name,
            EmoteID:   pmsg.Emotes[0].ID,
            EPM:       1,
        }

但是当我事先检查价值是否存在时,我无法增加EPM的价值

_, exists := bot.epm[pmsg.Emotes[0].Name]
    if exists {
        bot.epm[pmsg.Emotes[0].Name].EPM++
    } 

为什么编译器会抛出错误

无法分配到bot.epm [pmsg.Emotes [0] .Name] .EPM

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您必须先将结构分配给变量,更新该值,然后再将其存储回地图中:

e, exists := bot.epm[pmsg.Emotes[0].Name]
    if exists {
        e.EPM++
        bot.epm[pmsg.Emotes[0].Name] = e
    } 

您可以在此处找到更多详细信息:Access Struct in Map (without copying)