How to update a struct property in a map

Issue

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?

Solution

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.

Answered By – Iain Duncan

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.