Created
August 31, 2017 16:10
-
-
Save JekaMas/55f9eb2c4980b5054341f65cb128b1cb to your computer and use it in GitHub Desktop.
Golang slice flatten
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 ( | |
"errors" | |
"fmt" | |
) | |
func Flatten(arr interface{}) ([]int, error) { | |
return doFlatten([]int{}, arr) | |
} | |
func doFlatten(acc []int, arr interface{}) ([]int, error) { | |
var err error | |
switch v := arr.(type) { | |
case []int: | |
acc = append(acc, v...) | |
case int: | |
acc = append(acc, v) | |
case []interface{}: | |
for i := range v { | |
acc, err = doFlatten(acc, v[i]) | |
if err != nil { | |
return nil, errors.New("not int or []int given") | |
} | |
} | |
default: | |
return nil, errors.New("not int given") | |
} | |
return acc, nil | |
} | |
func main() { | |
res, err := Flatten([]interface{}{[]interface{}{1, 2, []int{3}}, 4}) | |
fmt.Println(res, err) | |
} |
So Go 1.18 already have generics, what you gonna do now?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I bet!