This question already has an answer here:
I am super confused about this, I have:
func getKind(v interface{}) string {
rt := reflect.TypeOf(v)
switch rt.Kind() {
case reflect.Slice:
return "slice"
case reflect.Array:
return "array"
default:
return "unknown"
}
}
func FlattenDeep(args ...interface{}) []interface{} {
list := []interface{}{}
for _, v := range args {
kind := getKind(v)
if kind != "unknown" {
for _, z := range FlattenDeep((v.([]interface{}))...) { // FAILS HERE
list = append(list, z)
}
} else {
list = append(list, v);
}
}
return list;
}
the error is:
panic: interface conversion: interface {} is []func(http.HandlerFunc) http.HandlerFunc, not []interface {}
I don't understand, I thought a slice of anything could be converted to a slice of interface{}
I think I fixed the runtime error by doing this:
for _, v := range args {
kind := getKind(v)
if kind != "unknown" {
a, ok := v.([]interface{})
if ok == false {
panic("o fuk")
}
for _, z := range FlattenDeep(a...) {
list = append(list, z)
}
} else {
list = append(list, v);
}
}
still feels wrong tho, why Go? why
</div>
The types are not equivalent, as stated in the comments.
The operator you are attempting to use is called a "type assertion" not a "type conversion" for a reason. It does not manipulate the underlying data in any way. It merely asserts that the underlying data can be treated as if it were the asserted type (and in the single assignment form that you used, will panic if the type is incorrect).
I'll skip the explanation of why this doesn't work and go directly to answering the following question
Jesus, I thought at the very least slices/arrays could be generic, wtf am I supposed to do lol
Define the following function:
func toIfaceSlice(any interface{}) []interface{} {
var out []interface{}
rv := reflect.ValueOf(any)
for i := 0; i < rv.Len(); i++ {
out = append(out, rv.Index(i).Interface())
}
return out
}
And use it to convert v
before recursing into FlattenDeep
.
Note: for brevity, I left out any optimizations and error checking.