dictionary - 无法增加 map 中结构的值

标签 dictionary go struct

我有一个这样的结构

type EPMEmote struct {
    EmoteID   string
    EmoteCode string
    EPM       int64
} 

在这张 map 内

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

我做错了什么?

最佳答案

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

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)

关于dictionary - 无法增加 map 中结构的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38293924/

相关文章:

python - 列表字典的笛卡尔积 - 带排序

c++ - 使用 mpz_t 作为 std::map 的键

go - 输入自定义电子邮件声明时无法创建 JWT token

c - 什么时候应该 typedef struct 与 pointer to struct?

c# - 将 C# 结构编码到 native C 库中

dictionary - 使用具有不可比较对象的 Map

go - 如何在 Prometheus 中正确检测区域和环境信息?

go - SFTP 进入错误 : User does not have appropriate read permission

在相同的结构类型中构建结构?

python - 在字典中查找符合特定条件的集合