访问映射值内的结构字段(不复制) [英] Accessing struct fields inside a map value (without copying)

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

问题描述

假设如下

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?

我知道您可以通过复制结构体、更改副本并复制回映射来实现这一点——但这是一个代价高昂的复制操作.

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.

推荐答案

根本问题是您无法获取地图中项目的地址.你可能认为编译器会重新排列 users[5].name = "Mark" 到这个

The fundamental problem is that you can't take the address of an item within a map. You might think the compiler 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 gives the maps the freedom to re-order things at will to use memory efficiently.

在地图中显式更改某些内容的唯一方法是为其分配值,即

The only way to change something explicitly in a map is to assign value 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 have the disadvantage of using more memory and more memory allocations, which may outweigh the copying way above - only you and your application can tell that.

第三种选择是使用切片 - 如果您将 users := make(map[int]User) 更改为 users := make([]User),您的原始语法可以完美运行, 10)

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天全站免登陆