Appending to slices in map of structs - values not set

I’m trying to append a string to a slice in struct, which is part of a map. Here’s an example that shows the behavior I’m seeing:

package main

import (
	"fmt"
)

type Person struct {
   Userid string
   Nicknames []string
}

var people map[string]Person

func addNickname( person string, nickname string ) {
    	subject := people[person]
    	subject.Nicknames = append( people[person].Nicknames, nickname )
    	fmt.Println("In method - subject: ", subject.Nicknames )
    	fmt.Println("In method - people: ", people[person].Nicknames )
}

func main() {
    	elizabeth := Person{ Userid: "emp01" }
 	people = make(map[string]Person)
    	people["elizabeth"] = elizabeth
    	fmt.Println("People: ", people )

    	addNickname( "elizabeth", "betsy" )
    	fmt.Println("Outside method: ", people["elizabeth"].Nicknames )

    	addNickname( "elizabeth", "liz" )
    	fmt.Println("Outside method: ", people["elizabeth"].Nicknames )

    	addNickname( "elizabeth", "lizzy" )
    	fmt.Println("Outside method: ", people["elizabeth"].Nicknames )	
}

I would expect people[“elizabeth”].Nicknames == [ “betsy”, “liz”, “lizzy” ] but while the subject gets set, the slice in the map doesn’t.

Code is in the Go Playground at https://play.golang.org/p/VejqTd0rltR

Sorry if this is a stupid question, I can’t find an answer and I’ve been looking/experimenting for hours!

In addNickname you’re never appending to the value in the map directly, but to a copy of it (subject).

If you want to make the changes to the map, you’d either have to update the value in the map after making your changes: https://play.golang.org/p/sCr0B2QRKEl
Or update your map to hold a pointer to Person so that subject is modifying the value from the map: https://play.golang.org/p/8AZ2eLx0weh

2 Likes