英文:
Golang removing nil from slice of interface{}
问题
从interface{}的切片中删除"nil"并生成一个新的interface{}切片的最佳方法是什么?
切片 := []interface{}{1, nil, "string", nil}
我脑海中没有好的解决方案。
英文:
What is the best way to remove "nil" from slice of interface{} and generating a new slice of interface{}?
Slice := []interface{}{1, nil, "string", nil}
Nothing good comes to my mind ?
答案1
得分: 8
新切片 := make([]interface{}, 0, len(切片))
for _, 项 := range 切片 {
if 项 != nil {
新切片 = append(新切片, 项)
}
}
英文:
newSlice := make([]interface{}, 0, len(Slice))
for _, item := range Slice {
if item != nil {
newSlice = append(newSlice, item)
}
}
答案2
得分: 2
除非出于其他原因,否则可以在不分配新切片的情况下完成此操作:
things := []interface{}{
nil,
1,
nil,
"2",
nil,
3,
nil,
}
for i := 0; i < len(things); {
if things[i] != nil {
i++
continue
}
if i < len(things)-1 {
copy(things[i:], things[i+1:])
}
things[len(things)-1] = nil
things = things[:len(things)-1]
}
fmt.Printf("%#v", things)
输出:
[]interface {}{1, "2", 3}
你可以在这里进行测试,关于切片操作的更多信息可以在这里找到。
英文:
Unless needed for other reasons, this can be done without allocating a new slice:
things := []interface{}{
nil,
1,
nil,
"2",
nil,
3,
nil,
}
for i := 0; i < len(things); {
if things[i] != nil {
i++
continue
}
if i < len(things)-1 {
copy(things[i:], things[i+1:])
}
things[len(things)-1] = nil
things = things[:len(things)-1]
}
fmt.Printf("%#v", things)
Output:
[]interface {}{1, "2", 3}
You can play with that here, and you can find more information about slice operations here.
答案3
得分: 1
你也可以像这个例子一样使用类型切换:
slice := []interface{}{1, nil, "string", nil}
newSlice := make([]interface{}, 0, len(slice))
for _, val := range(slice){
switch val.(type) {
case string, int: // 添加你想要填充newSlice的类型
newSlice = append(newSlice, val)
}
}
fmt.Printf("newSlice: %v\tType: %T\n", newSlice, newSlice)
输出结果:
newSlice: [1 string] Type: []interface {}
你可以在Go Playground中查看完整的示例。
英文:
You can also use type switches like this example:
slice := []interface{}{1, nil, "string", nil}
newSlice := make([]interface{}, 0, len(slice))
for _, val := range(slice){
switch val.(type) {
case string, int: // add your desired types which will fill newSlice
newSlice = append(newSlice, val)
}
}
fmt.Printf("newSlice: %v\tType: %T\n", newSlice, newSlice)
Output:
newSlice: [1 string] Type: []interface {}
You can see the full example within The Go Playground
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论