flatten arguments list, where arguments might be slices or arrays

若如初见. 提交于 2019-12-10 00:08:34

问题


If I have a func like this:

func AcceptsAnything(v ...interface{}){
  args =: FlattenDeep(v);  // flatten any arrays or slices
}

I am trying to implement FlattenDeep:

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" {
        list = append(list, FlattenDeep(v)...)  // does not compile
     } else{
        list = append(list, v);
       }
    }
   return list;
}

but I don't know how to append multiple items to the list at once. Should I just loop over the results of FlattenDeep or is there a way to spread the results and append them to the list?

This might work:

func FlattenDeep(args ...interface{}) []interface{} {
    list := []interface{}{}

    for _, v := range args {

        kind := getKind(v);
        if kind != "unknown" {
            for _, z := range FlattenDeep((v.([]interface{})...) {
                list = append(list, z)
            }

        } else {
            list = append(list, v);
        }
    }
    return list;
}

but I am looking for something a little less verbose if possible


回答1:


Here's how to flatten arbitrary slices and arrays to a []interface{}:

func flattenDeep(args []interface{}, v reflect.Value) []interface{} {

    if v.Kind() == reflect.Interface {
        v = v.Elem()
    }

    if v.Kind() == reflect.Array || v.Kind() == reflect.Slice {
        for i := 0; i < v.Len(); i++ {
            args = flattenDeep(args, v.Index(i))
        }
    } else {
        args = append(args, v.Interface())
    }

    return args
}

func AcceptsAnything(v ...interface{}) {
    args := flattenDeep(nil, reflect.ValueOf(v))
    fmt.Println(args)
}

Run it on the Playground

If the function must handle slice and array types with an arbitrary element type, then the application must iterate through the slice or array using the reflect API to get the values into an []interface{}.

If you only need to flatten []interface{}, then the reflect API is not needed:

func flattenDeep(args []interface{}, v interface{}) []interface{} {
    if s, ok := v.([]interface{}); ok {
        for _, v := range s {
            args = flattenDeep(args, v)
        }
    } else {
        args = append(args, v)
    }
    return args
}

func AcceptsAnything(v ...interface{}) {
    args := flattenDeep(nil, v)
    fmt.Println(args)
}

Run it on the Playground.



来源:https://stackoverflow.com/questions/53878197/flatten-arguments-list-where-arguments-might-be-slices-or-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!