英文:
Initialize array of interfaces in Golang
问题
这是一个变量的示例:
names := []interface{}{"first", "second"}
如何从一个字符串数组动态初始化它?
英文:
Here is an example of variable:
names := []interface{}{"first", "second"}
How can it be initialized dynamically, from an array of strings?
答案1
得分: 53
这是要翻译的内容:
strs := []string{"first", "second"}
names := make([]interface{}, len(strs))
for i, s := range strs {
names[i] = s
}
最简单的方式是这样的。
英文:
strs := []string{"first", "second"}
names := make([]interface{}, len(strs))
for i, s := range strs {
names[i] = s
}
Would be the simplest
答案2
得分: 38
append
方法会初始化切片(如果需要),所以这个方法可以这样使用:
var names []interface{}
names = append(names, "first")
names = append(names, "second")
下面是对相同操作的变体,将更多的参数传递给append
:
var names []interface{}
names = append(names, "first", "second")
这个一行代码也可以实现:
names := append(make([]interface{}, 0), "first", "second")
还可以先将要添加到interface{}
切片中的字符串切片进行转换。
英文:
append
initializes slices, if needed, so this method works:
<!-- language: lang-go -->
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
:
<!-- language: lang-go -->
var names []interface{}
names = append(names, "first", "second")
This one-liner also works:
<!-- language: lang-go -->
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.
答案3
得分: 6
你可以使用interface{}数组来构建它。
values := make([]interface{}, 0)
values = append(values, 1, 2, 3, nil, 4, "ok")
然后在使用值时检查类型。
for _, v := range values {
if v == nil {
fmt.Println("它是一个nil")
} else {
switch v.(type) {
case int:
fmt.Println("它是一个int")
case string:
fmt.Println("它是一个string")
default:
fmt.Println("我不知道它是什么")
}
}
}
英文:
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")
}
}
}
答案4
得分: -2
请尝试这个:
new([]interface{})
演示:https://play.golang.org/p/mEyhgQJY277
答案5
得分: -13
另一种方法:
strs := []string{"first", "second"}
var names []string
names = append(names, strs...)
英文:
another way:
strs := []string{"first", "second"}
var names []string
names = append(names, strs...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论