This question already has an answer here:
I'm trying to write a function that can take any type (more specifically, trying to get it to take any type of protobuffer, but I'll settle for being more broadly generic if I have to). Based on what I've read, it seems like it can be done like this:
func processSlice(mySlice []interface{}) void{
// Do stuff in here
}
When I try to use this with a slice of protos, though, I get the following error:
cannot use myProtoSlice (type []*MyProto) as type []interface{} in argument to processSlice
</div>
As the error clearly depicts:
cannot use myProtoSlice (type []*MyProto) as type []interface{} in argument to processSlice
[]interface{}
of interface is not interface{}
type it is different. Golang is strict about types.
Change the slice of interface to just interface to wrap the value you are receiving in your function. Modify below code:
func processSlice(mySlice []interface{}) void{
// Do stuff in here
}
To passing an interface
func processSlice(mySlice interface{}) void{
// Do stuff in here
}
You can't cast slices from a slice of one type to another (as you can types), it would be expensive, and they decided it was better to force you to be explicit.
It would probably be less painful to simply write the function for each slice type you actually need to handle (if you know the types and there are not many).