Home >Backend Development >Golang >Why Does Retrieving Pointers to Interfaced Values Raise an Exception?
Retrieving Pointers to Interfaced Values
Attempting to obtain a pointer to a value stored within an interface can raise an exception, as illustrated by the code below:
<code class="go">import "container/list" type retry struct{} el := list.New().PushBack(retry{}) p := &el.Value.(retry)</code>
This results in an error stating that the address of el.Value.(retry) cannot be taken. This behavior is not limited to structs; it applies to any type stored in an interface.
Understanding Interface Value Representation
To comprehend this restriction, consider the internal representation of an interface value. It consists of two words:
Crucially, the contained value is owned by the interface variable. Furthermore, the storage for this value may be reused when a new value is assigned to the interface.
Consequences of Allowable Pointer Retrieval
Understanding these principles, consider the following code:
<code class="go">var v interface{} v = int(42) p := GetPointerToInterfaceValue(&v) // a pointer to an integer holding 42 v = &SomeStruct{...}</code>
Here, the storage used for the integer has been repurposed to hold a pointer to a struct. As a result, dereferencing *p now produces an integer representation of the pointer to the SomeStruct. This behavior has the potential to undermine the type system.
Alternative Solutions
To avoid this issue, consider storing pointers to structs instead of structs themselves in the list. Alternatively, you may pass *list.Element values as references to the contained structures.
The above is the detailed content of Why Does Retrieving Pointers to Interfaced Values Raise an Exception?. For more information, please follow other related articles on the PHP Chinese website!