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

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

问题描述

我正在尝试将一个结构切片分配给切片 []interface{}(以传递到 AppEngine 的 datastore.PutMulti.然而,这会导致编译错误,因为这两种类型显然不兼容:
不能在赋值中使用 type[]*MyStruct 作为 type []interface { }

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

基本上我有:

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

有没有办法将 src 复制到 dest 而不复制每个元素一次?

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天全站免登陆