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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3