gempir
gempir

Reputation: 1901

Can't increase value of struct in map

I have a struct like this

type EPMEmote struct {
    EmoteID   string
    EmoteCode string
    EPM       int64
} 

inside this map

map[string]EPMEmote

I can add stuff easily like this:

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

but I can't increase the value of EPM when I check beforehand if the value exists

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

Why does the compiler throw the error

cannot assign to bot.epm[pmsg.Emotes[0].Name].EPM

What am I doing wrong?

Upvotes: 1

Views: 57

Answers (1)

abhink
abhink

Reputation: 9116

You must first assign the struct to a variable, update the value and then store it back in the map again:

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

You can find more details here: Access Struct in Map (without copying)

Upvotes: 2

Related Questions