anynil.go (807B)
1 package anynil 2 3 import "reflect" 4 5 // Is returns true if value is any type of nil. e.g. nil or []byte(nil). 6 func Is(value any) bool { 7 if value == nil { 8 return true 9 } 10 11 refVal := reflect.ValueOf(value) 12 switch refVal.Kind() { 13 case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: 14 return refVal.IsNil() 15 default: 16 return false 17 } 18 } 19 20 // Normalize converts typed nils (e.g. []byte(nil)) into untyped nil. Other values are returned unmodified. 21 func Normalize(v any) any { 22 if Is(v) { 23 return nil 24 } 25 return v 26 } 27 28 // NormalizeSlice converts all typed nils (e.g. []byte(nil)) in s into untyped nils. Other values are unmodified. s is 29 // mutated in place. 30 func NormalizeSlice(s []any) { 31 for i := range s { 32 if Is(s[i]) { 33 s[i] = nil 34 } 35 } 36 }