Skip to content

Instantly share code, notes, and snippets.

@JekaMas
Created August 31, 2017 16:10
Show Gist options
  • Save JekaMas/55f9eb2c4980b5054341f65cb128b1cb to your computer and use it in GitHub Desktop.
Save JekaMas/55f9eb2c4980b5054341f65cb128b1cb to your computer and use it in GitHub Desktop.
Golang slice flatten
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)
}
@saginadir
Copy link

oh I only wish golang had generics already so we can create a normal flatten function for all cases..

@JekaMas
Copy link
Author

JekaMas commented Sep 23, 2020

oh I only wish golang had generics already so we can create a normal flatten function for all cases..

I bet!

@ii64
Copy link

ii64 commented Jan 17, 2022

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