0
votes

How can I cast an interface{} to []interface{} ?

rt := reflect.ValueOf(raw)
switch rt.Kind() {
case reflect.Slice:
    src := raw.([]interface{}) //this operation errors out
    for _,_ :=  range src {
        //some operation
    }  
}

I get an error panic: interface conversion: interface {} is []string, not []interface {} I want make this method generic enough to handle any type, not a fixed type.

I'm very new to Go and I'm stuck with this problem, most likely I'm doing it wrong. Any suggestion how can I get around this ?

Edit: Some operation is json.Marshal which return byte array.

What I'm really trying to do: I have a function that receives interface type, if it is an array/slice then I would like to run json.Marshal on each item rather than apply it as a whole. Basically, I'm trying to break up the JSON blob if the first level object is an array, and yes it needs to be generic.

1
"I want to make this method generic" and "I'm very new to Go" almost always means you're going down the wrong road. Do not create complicated things based on reflection to save three lines of simple code; just write the three lines of simple code and move on. What "some operation" do you have in mind that you could apply to every possible type? Or is there really a small number of types you're actually dealing with? (Sounds like you want an interface, not reflection.) If you're trying to write a generic map() or filter() function, stop. If there were a good way to do that, it'd be in stdlib. - Rob Napier
@RobNapier I've added some more information in the original post, if that helps to make it clear. Thanks! - TiN

1 Answers

2
votes

As the error message states, a []string is not an []interface{}. See the FAQ for an explanation.

Use the reflect API do to this generically:

v := reflect.ValueOf(raw)
switch v.Kind() {
case reflect.Slice:
    for i := 0; i < v.Len(); i++ {
        elem := v.Index(i).Interface()
        // elem is an element of the slice
    }
}

Run it on the Playground.