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

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

问题描述

假设以下内容

type User struct {
    name string
}

users := make(map[int]User)

users[5] = User{"Steve"}

为什么无法访问现在存储在地图中的struct实例?

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