Created
March 18, 2020 06:13
-
-
Save bdragon/de6eb02c7445e078dffea4600847b189 to your computer and use it in GitHub Desktop.
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" | |
) | |
// 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