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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-10 13:07:10310browse

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

Converting a Slice of Structs into Slice of Empty Interface

When passing data to AppEngine's datastore.PutMulti function, it requires a slice of []interface{}. However, this can lead to compilation errors if you attempt to assign a slice of structs, []*MyStruct, to the []interface{} slice.

The error arises because the Go compiler considers these two types incompatible, resulting in a failure to assign src to dest.

Solution

Unfortunately, there is no direct way to copy a slice of structs into a slice of empty interface without copying each element individually. This is because casting a struct to an interface creates a wrapped version of the struct. An interface contains a pointer to the original type and a descriptor for the type itself. Hence, to properly wrap each struct, you must copy them one by one.

The above is the detailed content of How to 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!

Statement:
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