4

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?

djd
  • 4,988
  • 2
  • 25
  • 35
  • In Go, assignment (=) is different from copying (built-in function 'copy'). –  Feb 03 '12 at 19:26
  • I discovered that the go1 beta for app engine has changed the signature for `datastore.PutMulti` so that the above does work anyway. Hurrah! – djd Feb 10 '12 at 03:38

1 Answers1

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.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • That is what I feared. The fact that it takes some "work" to cast in the single case explains why the compiler won't just do it for you with slices. Oh well! – djd Feb 02 '12 at 23:43
  • Note that the reason for having to do this is a trade off between easy conversion to interfaces and indirection at the struct level. – Jesse Feb 09 '12 at 10:39