英文:
Converting slice of structs to slice of empty interface
问题
我试图将一个结构体切片分配给一个切片[]interface{}
(以便传递给AppEngine的datastore.PutMulti
)。然而,这会导致编译错误,因为这两种类型显然不兼容:无法将类型[]*MyStruct用作类型[]interface{}进行赋值
基本上我有:
var src []*MyStruct
var dest []interface{}
…
dest = src // 这一行失败了。
有没有办法将src
复制到dest
而不是逐个复制每个元素?
英文:
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
得分: 6
你将不得不逐个复制。没有其他办法。
如果这有助于接受,你应该考虑到将结构体包装在接口中实际上是在内存级别上进行包装。接口包含对原始类型的指针和对类型本身的描述符。当将单个结构体转换为接口时,实际上是在进行包装。因此,为了将结构体包装在接口中,逐个复制它们是必要的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论