從接口切片中刪除「nil」並生成新的接口切片的最佳方法是什麼?Golang從接口切片中刪除nil {}
Slice := []interface{}{1, nil, "string", nil}
沒有什麼好的在我心中?
從接口切片中刪除「nil」並生成新的接口切片的最佳方法是什麼?Golang從接口切片中刪除nil {}
Slice := []interface{}{1, nil, "string", nil}
沒有什麼好的在我心中?
newSlice := make([]interface{}, 0, len(Slice))
for _, item := range Slice {
if item != nil {
newSlice = append(newSlice, item)
}
}
您還可以使用式開關這樣的例子:
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)
輸出:
newSlice: [1 string] Type: []interface {}
你可以看到內The Go Playground
字面上_nothing_想到完整的例子嗎? – JimB
我已經遍歷範圍並檢查爲零。 –