Initialize array of interfaces in Golang

append initializes slices, if needed, so this method works:

var names []interface{}
names = append(names, "first")
names = append(names, "second")

And here is a variation of the same thing, passing more arguments to append:

var names []interface{}
names = append(names, "first", "second")

This one-liner also works:

names := append(make([]interface{}, 0), "first", "second")

It's also possible to convert the slice of strings to be added to a slice of interface{} first.


strs := []string{"first", "second"}
names := make([]interface{}, len(strs))
for i, s := range strs {
    names[i] = s
}

Would be the simplest

Tags:

Go