N P
N P

Reputation: 2619

Having multiple options in a case and then a loop within the case go

I have a function that accepts an interface{} I then do a switch, case on the type and if it's a slice I want to iterate over the elements. The issue I'm having is I can't have multiple options in the case selector, for example I can't seem to have []int, []float32 and then do a range over the values.

What I want to do is something like this

func digestCollection(obj interface{}) ([]byte, error) {

    switch v := obj.(type) {
    case []int64, []float64:
      for _, values := range v {
        // do something with v whether its an int or float
     }
    }
}

But I get an error saying I can't iterate over interface.

Upvotes: 1

Views: 244

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51542

In a type switch, if there is a single type case, then v is of that type:

switch v:=obj.(type) {
   case []int64:
     // Here, v is []int64
   case []float64:
     // here, v is []float64
}

However if there are multiple cases, or if it is the default case, then the type of v is the type of obj:

switch v:=obj.(type) {
   case []int64,[]float64:
   // Here, type of v is type of obj

because v cannot have a definite type if it is either an int array or a float64 array. The code generated for the two would be different.

You can try using reflection to go through the array, or write two loops, one for int and one for float64.

Upvotes: 2

Related Questions