简体   繁体   中英

Golang updating maps and variables in an object

I've found some behavior that seems a little strange, and it would be nice if someone could explain to me why it works this way.

Let's say we have a struct / object like this:

type Game struct {
    players map[string]Profile
}

type Profile struct {
    name string
    things map[string]string
}

Now let's say later on we call a Game method like this:

func (g *Game) someMethod(playerName string) {
    p, _ := g.players[playerName]
    fmt.Println("P Name:  " + p.name)
    fmt.Println("Map contents:  " + p.things["something"])

    // let's assume here p.name currently equals "bob" and p.things["something"] currently equals "this"

    p.name = "fred"
    p.things["something"] = "that"
}

The very first time we call someMethod(), p.name will equal "bob" and p.things["something"] will equal "this". After updating the values, if we immediately checked them again while still inside the method, p.name would equal "fred" and p.things "that".

However the next time we call this method, p.things will still equal "that" but p.name goes back to equaling "bob" instead of having the updated value of "fred". The only way I've found around this is to add this code after p.name has been updated:

g.players[playerName] = p

So, my question is, why does updating the map within the p object successfully update it so the next time we retrieve p from the Game object, p's map has the new data, but when we update p.name it reverts to the old value unless we manually add the p object back to the Game object's map?

p within someMethod is a copy of the profile struct. If you want to update the profile within the map, you will need to use a pointer, and a map of type map[string]*Profile

As for p.things , even though p is a copy of the struct, the map itself contains a reference to the underlying date. In other words, you don't need a pointer to a map to manipulate it's contents, and you rarely use a pointer to a map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM