Golang从接口切片中删除nil值

huangapple go评论117阅读模式
英文:

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,
		&quot;2&quot;,
		nil,
		3,
		nil,
	}

	for i := 0; i &lt; len(things); {
		if things[i] != nil {
			i++
			continue
		}

		if i &lt; len(things)-1 {
			copy(things[i:], things[i+1:])
		}

		things[len(things)-1] = nil
		things = things[:len(things)-1]
	}

	fmt.Printf(&quot;%#v&quot;, things)

Output:

[]interface {}{1, &quot;2&quot;, 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, &quot;string&quot;, 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(&quot;newSlice: %v\tType: %T\n&quot;, newSlice, newSlice)

Output:

newSlice: [1 string]	Type: []interface {}

You can see the full example within The Go Playground

huangapple
  • 本文由 发表于 2016年12月1日 06:37:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/40899548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定