Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize array of interfaces in Golang

Tags:

go

Here is an example of variable:

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

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

like image 375
Kir Avatar asked Jan 06 '14 16:01

Kir


People also ask

How do you declare an array of interfaces in Golang?

You can use interface{} array to build it. Then check the type when using the value. Save this answer.

How do I initialize an interface in Golang?

To create interface use interface keyword, followed by curly braces containing a list of method names, along with any parameters or return values the methods are expected to have.

What is interface {} Golang?

interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.

Is slice an interface in Golang?

The slice of interfaces is not a type itself, it is merely a “collection” of individual interfaces. Or in other words, each item in the anything “collection” is an empty Interface{}.


3 Answers

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

Would be the simplest

like image 200
val Avatar answered Oct 22 '22 19:10

val


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.

like image 44
Alexander Avatar answered Oct 22 '22 19:10

Alexander


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")
        }
    }
}
like image 6
Vincent Xie Avatar answered Oct 22 '22 21:10

Vincent Xie