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!