Here is an example of variable:
names := []interface{}{"first", "second"}
How can it be initialized dynamically, from an array of strings?
You can use interface{} array to build it. Then check the type when using the value. Save this answer.
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.
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.
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{}.
strs := []string{"first", "second"}
names := make([]interface{}, len(strs))
for i, s := range strs {
names[i] = s
}
Would be the simplest
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.
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")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With