dongmou3615 2014-07-29 01:34
浏览 17
已采纳

Golang更新对象中的地图和变量

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?

  • 写回答

1条回答 默认 最新

  • dongyong2063 2014-07-29 01:39
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误