golangはスライスの要素を削除し、スライス内のゼロ値を削​​除します



Golang Delete An Element Slice



func remove(slice []interface{}, elem interface{}) []interface{}{ if len(slice) == 0 { return slice } for i, v := range slice { if v == elem { slice = append(slice[:i], slice[i+1:]...) return remove(slice,elem) break } } return slice } func removeZero(slice []interface{}) []interface{}{ if len(slice) == 0 { return slice } for i, v := range slice { if ifZero(v) { slice = append(slice[:i], slice[i+1:]...) return removeZero(slice) break } } return slice } //To judge whether a value is zero, only string, float, int, time and their respective pointers are supported. '%' and '%%' also belong to the zero value category, and the scenario is like statement func IfZero(arg interface{}) bool { if arg == nil { return true } switch v := arg.(type) { case int, int32, int16, int64: if v == 0 { return true } case float32: r:=float64(v) return math.Abs(r-0)<0.0000001 case float64: return math.Abs(v-0)<0.0000001 case string: if v == '' || v == '%%' || v == '%' { return true } case *string, *int, *int64, *int32, *int16, *int8, *float32, *float64, *time.Time: if v == nil { return true } case time.Time: return v.IsZero() default: return false } return false }