无法获取地图元素的地址 [英] Cannot take the address of map element

查看:73
本文介绍了无法获取地图元素的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找出原因

x:= odsMap[segRef]
x.GetValue("@OriginDestinationKey")

可以,但是不能:

odsMap[segRef].GetValue("@OriginDestinationKey")

最后一个代码段显示以下错误:

The last snippet prints the following errors:

cannot call pointer method on odsMap[segRef]go
cannot take the address of odsMap[segRef]


$ b $的地址b

这些错误在编译时(而不是运行时)发生。因此,我的主要问题是为什么我需要一个中间变量 x 来访问该函数?

关于类型变量 odsMap map [string] XMLElement和 segRef

Regarding the type of the variables odsMap is a map[string] XMLElement and segRef is a string.

谢谢。

推荐答案

映射索引表达式不能寻址,因为添加新条目时映射的内部可能会改变,因此规范有意不允许使用其地址(这为映射实现提供了更大的自由度)。

Map index expressions are not addressable, because the internals of a map may change when a new entry is added to it, so the spec intentionally does not allow taking its address (this gives greater freedom for map implementations).

这意味着,如果您在地图中存储非指针,并且要调用具有指针接收器的存储值的方法,则需要获取非指针值的地址(以用作接收方),但是由于映射索引表达式不可寻址,因此会导致编译时错误。

This means if you store non-pointers in the map, and you want to call a method of a stored value that has a pointer receiver, that would require to take the address of the non-pointer value (to be used as the receiver), but since map index expressions are not addressable, that results in a compile-time error.

一种解决方法是将指针值存储在映射中,因此无需输入in的地址dex表达式,因为它已经是一个指针。可以在此答案中看到一个示例:为什么应构造函数返回地址的地址?如果我们使用以下类型:

A workaround is to store pointer values in the map, so there is no need to take the address of an index expression, because it's already a pointer. An example of this can be seen in this answer: Why should constructor of Go return address? If we have this type:

type My int

func (m *My) Str() string { return strconv.Itoa(int(*m)) }

这会产生相关的编译时错误:

This gives the compile-time error in question:

m := map[int]My{0: My(12)}
m[0].Str() // Error!

但这可行:

m := map[int]*My{}
my := My(12)
m[0] = &my // Store a pointer in the map

m[0].Str() // You can call it, no need to take the address of m[0]
           // as it is already a pointer

另一个选择是将其分配给可以获取其地址的局部变量,然后在该变量上调用指针方法。尽管必须小心,就像该方法具有指针接收器一样,它可能会修改指向的对象或其组件(例如结构的字段),这将不会反映在映射中存储的值中。如果沿着这条路走,您可能必须将值重新分配给地图中的键以具有更新的值。

Another option is to assign it to a local variable whose address can be taken, and call the pointer method on that. Care must be taken though, as if the method has pointer receiver, it might modify pointed object or its components (e.g. fields of a struct), which would not be reflected in the value stored in the map. If you go down this path, you might have to reassign the value to the key in the map to have the updated value.

如果有一个值的类型带有指针接收器的方法,最好将它(存储,传递)用作指针,而不是用作非指针值。

All-in-all, if you have a value whose type has methods with pointer receiver, you're better off using it (store, pass) as a pointer and not as a non-pointer value.

请参见相关问题:

非指针类型的指针方法

如何在Go中存储对操作结果的引用?

这篇关于无法获取地图元素的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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