在接口内部获取值的地址 [英] Take address of value inside an interface

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

问题描述

如何在接口内部获取值的地址?

How do I take the address of a value inside an interface?

我在list.List元素的接口中存储了一个结构:

I have an struct stored in an interface, in a list.List element:

import "container/list"
type retry struct{}
p := &el.Value.(retry)

但是我明白了:

cannot take the address of el.Value.(retry)

这是怎么回事?由于该结构存储在接口中,为什么我无法获得指向它的指针?

What's going on? Since the struct is stored in the interface, why can't I get a pointer to it?

推荐答案

要了解为什么不可能这样做,请考虑一下接口变量实际上是什么很有帮助.接口值占用两个词,第一个描述所包含值的类型,第二个要么(a)保存所包含的值(如果它适合单词内),要么(b)指向该值的存储指针(如果该值不适合一个单词).

To understand why this isn't possible, it is helpful to think about what an interface variable actually is. An interface value takes up two words, with the first describing the type of the contained value, and the second either (a) holding the contained value (if it fits within the word) or (b) a pointer to storage for the value (if the value does not fit within a word).

要注意的重要事项是(1)所包含的值属于接口变量,并且(2)当为变量分配新值时,可以重复使用该值的存储.知道这一点后,请考虑以下代码:

The important things to note are that (1) the contained value belongs to the interface variable, and (2) the storage for that value may be reused when a new value is assigned to the variable. Knowing that, consider the following code:

var v interface{}
v = int(42)
p := GetPointerToInterfaceValue(&v) // a pointer to an integer holding 42
v = &SomeStruct{...}

现在,整数的存储已被重用以保存指针,并且*p现在是该指针的整数表示.您可以看到它具有打破类型系统的能力,因此Go并没有提供执行此操作的方法(除了使用unsafe包之外).

Now the storage for the integer has been reused to hold a pointer, and *p is now an integer representation of that pointer. You can see how this has the capacity to break the type system, so Go doesn't provide a way to do this (outside of using the unsafe package).

如果需要指向要存储在列表中的结构的指针,则一种选择是将指针存储到列表中的结构,而不是直接存储结构值.另外,您可以传递*list.Element值作为对所包含结构的引用.

If you need a pointer to the structs you're storing in a list, then one option would be to store pointers to the structs in the list rather than struct values directly. Alternatively, you could pass *list.Element values as references to the contained structures.

这篇关于在接口内部获取值的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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