github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/nilcheck.go (about)

     1  package don
     2  
     3  import "reflect"
     4  
     5  func newNilCheck(zero any) func(v any) bool {
     6  	typ := reflect.TypeOf(zero)
     7  
     8  	// Return true for nil interface.
     9  	if typ == nil {
    10  		return func(v any) bool { return v == nil }
    11  	}
    12  
    13  	switch typ.Kind() {
    14  	case reflect.String, reflect.Ptr, reflect.Interface:
    15  		// Return true for empty string and nil pointer.
    16  		return func(v any) bool { return v == zero }
    17  	case reflect.Map:
    18  		// Return true for and nil map.
    19  		return func(v any) bool { return dataOf(v) == nil }
    20  	case reflect.Slice:
    21  		// Return true for nil slice.
    22  		return func(v any) bool { return (*reflect.SliceHeader)(dataOf(v)).Data == 0 }
    23  	default:
    24  		// Return false for all others.
    25  		return func(any) bool { return false }
    26  	}
    27  }