I am struggling with this for quite some time. I basically want to create a function that recursively join a string to an array.
Like this :
join ", " ["one","two","three"] should look like this "one, two, three"
I am struggling with this for quite some time. I basically want to create a function that recursively join a string to an array.
Like this :
join ", " ["one","two","three"] should look like this "one, two, three"
Something like this
package main
import (
"fmt"
"strings"
)
func flatJoin(sep string, args ...interface{}) string {
values := make([]string, 0)
for _, item := range args {
switch v := item.(type) {
case string:
values = append(values, v)
case []string:
values = append(values, v...)
case fmt.Stringer:
values = append(values, v.String())
default:
values = append(values, fmt.Sprintf("%v", v))
}
}
return strings.Join(values, sep)
}
func main() {
fmt.Println(flatJoin(", ", "basic", "other", []string{"here", "more", "inner"}))
}
http://play.golang.org/p/yY6YnZZAak
This supports only one level of flattening, but you can customize the recursion on your switch statement depending on what you are expecting.