【问题标题】:Can't increase value of struct in map无法增加地图中结构的值
【发布时间】:2016-07-10 16:14:15
【问题描述】:

我有一个这样的结构

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

我做错了什么?

【问题讨论】:

    标签: dictionary go struct


    【解决方案1】:

    您必须首先将结构分配给一个变量,更新值,然后再次将其存储回映射中:

    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)

    【讨论】:

    • 哦,有道理!非常感谢!
    猜你喜欢
    • 2013-04-06
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2020-07-15
    • 2020-02-06
    相关资源
    最近更新 更多