I'm writing a library and I want to return an array (or write to an array) of an unspecific type to the caller. The type can vary, depending on who calls - I can, however, create as many objects of said type from within my function. One way would be that the caller creates an array and the callee fills that - however, there is no way of telling how long this array is going to be. (Is there a way that the callee makes the caller's array bigger? Remember, the callee only sees x interface{}
...)
The other way which I chose because I don't see how above is possible, is that the caller gives me the pointer of his specific type and I redirect it to the array of objects which I created.
Below is my solution. My question: why is the array empty after the function call? They are pointing to the same array after my operation, they should be the same. Am I overlooking something? I thought about GC, but it couldn't be that fast, could it?
http://play.golang.org/p/oVoPx5Nf84
package main
import "unsafe"
import "reflect"
import "log"
func main() {
var x []string
log.Printf("before: %v, %p", x, x)
manipulate(&x)
log.Printf("after: %v, %p", x, x)
}
func manipulate(target interface{}) {
new := make([]string, 0, 10)
new = append(new, "Hello", "World")
log.Printf("new: %v, %p", new, new)
p := unsafe.Pointer(reflect.ValueOf(target).Pointer())
ptr := unsafe.Pointer(reflect.ValueOf(new).Pointer())
*(*unsafe.Pointer)(p) = ptr
}