Assigning Slice of Structs to Interface Slice
When attempting to assign a slice of structs ([]MyStruct) to a slice of interfaces ([]interface{}), you may encounter a compile-time error. This is because structs and interfaces have different memory representations.
Structs have their fields stored adjacent in memory, while interfaces are stored as a two-word pair, one for type information and one for the actual data. This difference prevents direct assignment.
Possible Solutions:
y := make([]interface{}, len(x)) for i, v := range x { y[i] = v }
type IMyStruct struct { MyStruct } func (i IMyStruct) Interface() interface{} { return i.MyStruct } x := []MyStruct{{5}, {6}} y := []interface{}{IMyStruct{x[0]}, IMyStruct{x[1]}}
var y interface{} y = x // No type conversion required
The above is the detailed content of How Can I Assign a Slice of Structs to a Slice of Interfaces in Go?. For more information, please follow other related articles on the PHP Chinese website!