将结构体切片转换为空接口切片

huangapple go评论63阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2012年2月3日 07:20:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/9121515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定