Skip to content

Instantly share code, notes, and snippets.

@kakysha
Last active November 21, 2017 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kakysha/1df43eda32e7c3fa7ab50e4ba1a803c2 to your computer and use it in GitHub Desktop.
Save kakysha/1df43eda32e7c3fa7ab50e4ba1a803c2 to your computer and use it in GitHub Desktop.
Go flatten slice implementation
package main
import (
"fmt"
"reflect"
)
// variadic argument to utilize Go slices expansion mechanism '...'
func flatten(input ...interface{}) (res []int) {
for _, val := range input {
v := reflect.ValueOf(val)
switch v.Kind() {
case reflect.Slice:
// so elegant, even I got impressed by myself with this '...)...' and recursion
res = append(res, flatten(v.Interface().([]interface{})...)...)
case reflect.Int:
res = append(res, v.Interface().(int))
default:
panic(fmt.Sprintf("incorrect input value: %s", v))
}
}
return
}
func main() {
var input = []interface{}{0, []interface{}{1, 2, []interface{}{3}}, 4}
fmt.Println(input)
var output []int = flatten(input)
fmt.Println(output)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment