"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to convert structure slices into empty interface slices in Go language?

How to convert structure slices into empty interface slices in Go language?

Posted on 2025-04-19
Browse:495

How Can I Convert a Slice of Structs to a Slice of Empty Interfaces in Go?

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.

Latest tutorial More>

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