Here is an example of variable:
names := []interface{}{"first", "second"}
How can it be initialized dynamically, from an array of strings?
strs := []string{"first", "second"}
names := make([]interface{}, len(strs))
for i, s := range strs {
names[i] = s
}
Would be the simplest
make: ``` names := []interface{}{} string_names := []string{"first", "second"} for _, v := range string_names { names = append(names, v) } ```[]interface{}{} initializes the array with zero length, and the length is grown (possibly involving copies) when calling append. This is usually not a problem, if your arrays are not ridiculously large. If they are, make initializes it with full length and never copies it (as the size is known from the start).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")
For Go 1.18 or later, this is also possible:
names := append([]any{}, "first", "second")
Yet another option is to first convert the slice of strings to be added to a slice of interface{} or any.
You can use interface{} array to build it.
values := make([]interface{}, 0)
values = append(values, 1, 2, 3, nil, 4, "ok")
Then check the type when using the value.
for _, v := range values {
if v == nil {
fmt.Println("it is a nil")
} else {
switch v.(type) {
case int:
fmt.Println("it is a int")
case string:
fmt.Println("it is a string")
default:
fmt.Println("i don't know it")
}
}
}
another way:
strs := []string{"first", "second"}
var names []string
names = append(names, strs...)