Converting Slice of Structs to Slice of Empty Interface
Assigning a slice of structs to a slice of empty interfaces is not straightforward due to type incompatibility, as seen in the following code:
type MyStruct struct { // ... } var src []*MyStruct var dest []interface{} dest = src // Compilation error
This error arises because the compiler identifies the two types as incompatible. To resolve this, one must copy each element manually:
for _, s := range src { dest = append(dest, s) }
Despite the tediousness of copying elements one by one, it is necessary because casting a struct to an interface involves wrapping the struct in an interface pointer and type descriptor. Copying each element separately ensures this wrapping process is performed correctly.
The above is the detailed content of How Can I Convert a Slice of Structs to a Slice of Empty Interfaces in Go?. For more information, please follow other related articles on the PHP Chinese website!