48

Here is an example of variable:

names := []interface{}{"first", "second"}

How can it be initialized dynamically, from an array of strings?

1
  • 10
    That's not an array, it's a slice. Commented Jan 7, 2014 at 1:46

5 Answers 5

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

Would be the simplest

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! BTW, I found another way without make: ``` names := []interface{}{} string_names := []string{"first", "second"} for _, v := range string_names { names = append(names, v) } ```
Absolutely. Be aware however that []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).
43

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.

Comments

6

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")
        }
    }
}

Comments

-2

Try this one:

new([]interface{})

Demo: https://play.golang.org/p/mEyhgQJY277

Comments

-13

another way:

strs := []string{"first", "second"}
var names []string
names = append(names, strs...)

1 Comment

It's not an interface, isn't it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.