samedi 14 février 2015

Golang: how to use interface{} type to insert a value into the middle of a slice?

I'm having difficulty getting my head around the usage of interface{} types with Go.


In this instance I have a function which inserts a value into the middle of a slice somewhere. It looks like this:



type mystruct {
a, b, c int
}

func insert(ar []mystruct, val mystruct, i int) []mystruct {
l := len(ar)
if l == cap(ar) {
tmp := make([]mystruct, l + 1, (l * 2) + 1)
copy(tmp, ar[0:i])
copy(tmp[i+1:], ar[i:])
ar = tmp
} else {
ar = ar[0:l+1]
copy(ar[i+1:], ar[i:])
}
ar[i] = val

return ar
}


I'd like for that function to be able to accept interface{} for both ar and val so that I could pass it a slice and value of any type and it would perform the insert without complaint.


From what I have read so far I believe this should be done with the reflect package. I have read the Rules of Reflection and various tutorials on reflection and interface{}, but I'm not sure how to approach this. I'd like to minimize overhead as much as possible, I understand reflection is going to slow the code down a bit but what is the most efficient way of doing this?


Thanks!






Aucun commentaire:

Enregistrer un commentaire