在地图中访问结构(不复制) [英] Access Struct in Map (without copying)

查看:66
本文介绍了在地图中访问结构(不复制)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下

 类型用户结构{
名称字符串
}

用户:= make(map [int]用户)

用户[5] =用户{Steve}

为什么现在不能访问现在存储在地图中的结构实例?

  users [5] .name =Mark

任何人都可以对如何访问映射存储的结构,或为什么它是不可能的逻辑?

注意



我知道你可以通过复制结构体,更改副本并将其复制回地图来实现这一目的 - 但这是一个昂贵的复制操作。



我也知道这个可以通过在我的地图中存储结构指针来完成,但我不想这样做。 解决方案

基本问题是你不能在地图上看到某件东西的地址。你可能会认为编译会将 users [5] .name =Mark重新排列成这个



<$ p $ > (& users [5])。name =Mark

但没有编译,给出这个错误

 不能取用户的地址[5] 

code>

这允许映射自由来随意重新排序以有效地使用内存。



实际上在map中改变某些东西的唯一方法就是分配给它,即

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

因此,我认为你必须与上面的副本一起居住,或者在地图中存储指针。存储指针的缺点是使用更多的内存和更多的内存分配,这可能会超过上面的复制 - 只有你和你的应用程序能够说明这一点。

第三种方法是使用切片 - 如果将用户:= make(map [int] User)改为 users:= make([ ] User,10)


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.

解决方案

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)

这篇关于在地图中访问结构(不复制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆