Home >Backend Development >Golang >Why Does Retrieving Pointers to Interfaced Values Raise an Exception?

Why Does Retrieving Pointers to Interfaced Values Raise an Exception?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 19:18:02302browse

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:

  • The first word contains the type information of the contained value.
  • The second word either stores the value itself (if it fits within a word) or a pointer to its storage (if the value exceeds the word size).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn