-2

Currently trying to learn Go.

I have the following function, but it only works when the team doesn't exist in the map already and it creates a new record in the map. It will not update the values if the team already has a struct in the map.

func AddLoss(teamMap map[string]TeamRow, teamName string) {
    if val, ok := teamMap[teamName]; ok {
        val.Wins++
        val.GamesPlayed++
    } else {
        newTeamRow := TeamRow{Losses: 1}

        teamMap[teamName] = newTeamRow
    }
}

I have updated the function to just replace the existing record with a brand new struct with the values I want, but that seems odd that I can't update the values in a map.

Can someone explain this to me, or point me in the right direction?

Tim
  • 1
  • 1
  • What do you mean "it only works when the team doesn't exist"? What happens when it does exist? What exactly is the observed behavior? – Jonathan Hall Mar 11 '19 at 18:09
  • 1
    You probably need to use `*TeamRow` rather than `TeamRow`. – Jonathan Hall Mar 11 '19 at 18:10
  • 1
    Use *TeamRow as suggested in previous comment or assign the value back to the map. See [Why do I get a “cannot assign” error when setting value to a struct as a value in a map?](https://stackoverflow.com/questions/32751537/why-do-i-get-a-cannot-assign-error-when-setting-value-to-a-struct-as-a-value-i), [Access Struct in Map (without copying)](https://stackoverflow.com/questions/17438253/access-struct-in-map-without-copying), ... – Charlie Tumahai Mar 11 '19 at 18:12
  • @Flimzy The values don't get updated is what is observed. The object keeps the same property values it was assigned when it was first created. – Tim Mar 11 '19 at 18:23
  • @ThunderCat Thank you for the link, that made a lot of sense. – Tim Mar 11 '19 at 18:37

1 Answers1

0

You have a map of string to the value of TeamRow so when you get the val out of the map it returns the value of the team, not a pointer to the team. If you make the map a string to the pointer of TeamRow then when you get the val out it will point to the memory that is stored in the map so values will persist beyond the scope of your AddLoss function. To do this simply add a * to the map declaration - teamMap map[string]*TeamRow though when you populate it you will then also need to store pointers in the map.

Iain Duncan
  • 3,139
  • 2
  • 17
  • 28