Addressing Values Inside Interfaces
In order to understand why it's not feasible to take the address of a value stored in an interface, it's crucial to delve into the nature of an interface variable. Essentially, an interface value consists of two components:
Two key aspects to note:
Consider the following code snippet:
<code class="go">var v interface{} v = int(42) p := GetPointerToInterfaceValue(&v) // a pointer to an integer holding 42 v = &SomeStruct{...}</code>
In this scenario, the storage previously holding the integer is repurposed to store a pointer. As a result, dereferencing *p now yields the numeric representation of the pointer.
To prevent compromising the type system, Go intentionally restricts this type of pointer retrieval (apart from unsafe package usage).
Alternative Solutions
If your requirement is to access pointers of structs stored in a list, consider these alternatives:
The above is the detailed content of Why Can\'t You Get the Address of a Value Stored in a Go Interface?. For more information, please follow other related articles on the PHP Chinese website!