Home > Backend Development > Golang > How Can I Convert a Slice of Structs to a Slice of Empty Interfaces in Go?

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

DDD
Release: 2024-12-05 10:07:15
Original
381 people have browsed it

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
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template