samedi 6 avril 2019

Cast a slice of a type to a slice of a interface the type implements?

I have an interface I and a type T that implements I.

My function takes a []I.

When I pass a slice of some Ts ([]T) to my function, the compiler sais that []T cannot be used as a []I - after some research, I found out that this is due to the different memory layouts.

The common solution seems to be the creation of a []I and appending each T instance from []T to it.

This is an O(n) operation.

Is there a technique I can use so that I don't have to process each T before I can even use my function that takes a []I?

Unfortunately, this doesn't seem to work:

var myInstances []T

myFunction(myInstances.([]I)) // <- myFunction() takes a []I





Aucun commentaire:

Enregistrer un commentaire