dongmi5177 2013-07-03 01:12
浏览 26
已采纳

在地图中访问结构(无复制)

Assuming the following

type User struct {
    name string
}

users := make(map[int]User)

users[5] = User{"Steve"}

Why isn't it possible to access the struct instance now stored in the map?

users[5].name = "Mark"

Can anyone shed some light into how to access the map-stored struct, or the logic behind why it's not possible?

Notes

I know that you can achieve this by making a copy of the struct, changing the copy, and copying back into the map -- but that's a costly copy operation.

I also know this can be done by storing struct pointers in my map, but I don't want to do that either.

  • 写回答

2条回答 默认 最新

  • dongrou2920 2013-07-03 09:08
    关注

    The fundamental problem is that you can't take the address of something in a map. You might think the compile would re-arrange users[5].name = "Mark" into this

    (&users[5]).name = "Mark"
    

    But that doesn't compile, giving this error

    cannot take the address of users[5]
    

    This is to allow maps the freedom to re-order things at will to use memory efficiently.

    The only way to change something actually in a map is to assign to it, i.e.

    t := users[5]
    t.name = "Mark"
    users[5] = t
    

    So I think you either have to live with the copy above, or live with storing pointers in your map. Storing pointers has the disadvantage of using more memory and more memory allocations which may outweigh the copying in the above - only you and your application can tell that.

    A third alternative is to use a slice - your original syntax works perfectly if you change users := make(map[int]User) to users := make([]User, 10)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题