将结构片转换为空的接口片 [英] Converting slice of structs to slice of empty interface

查看:138
本文介绍了将结构片转换为空的接口片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一片结构分配给 [] interface {} (以传入AppEngine的 datastore.PutMulti code>。但是,这会导致编译错误,因为这两种类型显然不兼容:

在赋值时不能使用type [] * MyStruct作为type [] interface {}
$ p
$ b基本上我有: var src [] * MyStruct
var dest [] interface {}
...
dest = src //这行失败。

无论如何复制 src dest 而不复制每个元素一次一个?

解决方案

您将不得不一次一个地复制。

如果它有助于接受这个问题,你应该考虑一个事实,即在接口中封装一个结构实际上确实将它包装在内存中一个接口包含一个指向原始类型的指针和一个类型描述符self。当将一个结构体转换为一个接口时,你真的包装它。因此,为了将结构包装在界面中,需要一次性复制它们。


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?

解决方案

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.

这篇关于将结构片转换为空的接口片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆