Converting slice of structs to slice of empty inte

2020-02-12 11:22发布

I'm trying to assign a slice of structs to a slice []interface{} (to pass into AppEngine's datastore.PutMulti. However, this is causing compilation errors as the two types are apparently incompatible:
cannot use type[]*MyStruct as type []interface { } in assignment

Basically I have:

var src []*MyStruct
var dest []interface{}
…
dest = src  // This line fails.

Is there anyway to copy src into dest without copying each element one-at-a-time?

1条回答
forever°为你锁心
2楼-- · 2020-02-12 12:16

You're going to have to copy one-at-a-time. There's no way around it.

If it helps to accept this, you should think about the fact that wrapping a struct in an interface really does actually wrap it at the memory level. An interface contains a pointer to the original type and a descriptor for the type itself. When casting a single struct to an interface, you're really wrapping it. So copying them one-at-a-time is necessary in order to wrap the structs up in the interface.

查看更多
登录 后发表回答