Home >Backend Development >Golang >How Can I Assign a Go Struct Array to an Interface Array?
Interface Array Assignment Conundrum in Go
In Go, the attempt to assign a struct array directly to an interface array, as shown below, yields a compile-time error:
x := []MyStruct{...} var y []interface{} y = x // Error: cannot use x as type []interface {}
This error stems from the fundamental difference in how struct types and interfaces are stored in memory. Interfaces are stored as two-word pairs, comprising type information and data, while struct types are stored as adjacent fields in memory.
Since these representations do not align, direct conversion between the two is not feasible. It is necessary to copy the elements individually to the destination slice.
To resolve this issue, consider one of the following options:
var y []interface{} y = make([]interface{}, len(x)) for i, v := range x { y[i] = v }
var y interface{} y = x
In the latter scenario, the interface holds an abstract reference to the underlying []MyStruct slice, allowing for polymorphic behavior.
The above is the detailed content of How Can I Assign a Go Struct Array to an Interface Array?. For more information, please follow other related articles on the PHP Chinese website!