Interface Slices and Struct Arrays in Go
In Go, assigning a slice of structs ([]MyStruct) to an interface slice ([]interface{}) is not directly possible. This is because structs and interfaces use different memory representations.
Struct fields are contiguous in memory, while interfaces are stored as type information and data pairs. This difference prevents direct conversion between the two.
Why Direct Assignment Fails
The compiler error when attempting to assign x (a slice of structs) to y (an interface slice) reflects this underlying difference. Go requires type compatibility for assignments, and the two types do not match.
Alternatives for Handling Generic Object Arrays
Despite the inability to directly assign struct arrays to interface slices, Go offers several alternative approaches for handling generic object arrays:
Example Code
// Copy Elements Individually var x []MyStruct = [...]MyStruct{{5}, {6}} var y []interface{} for _, v := range x { y = append(y, v) } // Interface Slices var x []MyStruct = [...]MyStruct{{5}, {6}} var y []interface{} = make([]interface{}, len(x)) for i, v := range x { y[i] = v } // Interface Wrapper type MyStructArrayWrapper interface { Get() []MyStruct } type MyStructArrayWrapperImpl struct { array []MyStruct } func (w *MyStructArrayWrapperImpl) Get() []MyStruct { return w.array } x := []MyStruct{MyStruct{5}, MyStruct{6}} var y interface{} = &MyStructArrayWrapperImpl{x}
The above is the detailed content of How Can I Assign a Go Slice of Structs to an Interface Slice?. For more information, please follow other related articles on the PHP Chinese website!