0

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
blackgreen
  • 34,072
  • 23
  • 111
  • 129
Reagankm
  • 4,780
  • 9
  • 27
  • 52
  • 1
    `[]interface{}` is not `interface{}`, it's a specific type (a slice of type `interface{}`). You must pass a `[]interface{}` to that function, but that slice can contain values of any type (or any mix of types). – Adrian Jul 30 '18 at 15:04
  • 1
    See the FAQ: https://golang.org/doc/faq#convert_slice_of_interface – JimB Jul 30 '18 at 15:04
  • try using something like `func processSlice(mySlice ...interface{}) void{ // Do stuff in here }` – Dhruv Pal Aug 27 '19 at 13:38

2 Answers2

3

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
}
Himanshu
  • 12,071
  • 7
  • 46
  • 61
3

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).

Kenny Grant
  • 9,360
  • 2
  • 33
  • 47