Skip to content

Instantly share code, notes, and snippets.

@pjulien
Created March 20, 2019 16:53
Show Gist options
  • Save pjulien/fa00e6e755a1416c3b197a0ec7815844 to your computer and use it in GitHub Desktop.
Save pjulien/fa00e6e755a1416c3b197a0ec7815844 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"reflect"
)
func flatten(v ...interface{}) {
flatenned := flattenDeep(nil, reflect.ValueOf(v))
fmt.Println(flatenned)
}
func flattenDeep(args []interface{}, v reflect.Value) []interface{} {
kind := v.Kind()
if kind == reflect.Interface {
v = v.Elem()
kind = v.Kind()
}
if kind == reflect.Array || 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 main() {
flatten([]interface{}{1, 2, []interface{}{3}}, []interface{}{4})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment