Skip to content

Instantly share code, notes, and snippets.

@bdragon
Created March 18, 2020 06:13
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 bdragon/de6eb02c7445e078dffea4600847b189 to your computer and use it in GitHub Desktop.
Save bdragon/de6eb02c7445e078dffea4600847b189 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"reflect"
)
// concat returns a slice of type t that contains the specified items.
// Each item is appended according to its type: if it has type t, it is
// appended; if it is a slice of values of type t, each of its elements
// is appended; values of other types are ignored.
func concat(t reflect.Type, items ...interface{}) interface{} {
out := reflect.MakeSlice(reflect.SliceOf(t), 0, len(items))
for _, item := range items {
v := reflect.ValueOf(item)
if v.Kind() == t.Kind() {
out = reflect.Append(out, v)
} else if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == t.Kind() {
out = reflect.AppendSlice(out, v)
}
}
return out.Interface()
}
func main() {
a := "foo"
b := []string{"bar", "baz"}
c := ([]string)(nil)
d := "qux"
fmt.Printf("%#v\n", concat(reflect.TypeOf(a), a, b, c, d))
// Output: []string{"foo", "bar", "baz", "qux"}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment