Last active
November 21, 2017 22:49
-
-
Save kakysha/1df43eda32e7c3fa7ab50e4ba1a803c2 to your computer and use it in GitHub Desktop.
Go flatten slice implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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