gitlab.com/evatix-go/core@v1.3.55/internal/reflectinternal/IsZeroReflectValue.go (about)

     1  package reflectinternal
     2  
     3  import "reflect"
     4  
     5  // IsZeroReflectValue
     6  //
     7  //  returns true if the current value is null
     8  //  or reflect value is zero
     9  //
    10  // Reference:
    11  //  - Stackoverflow Example : https://stackoverflow.com/a/23555352
    12  func IsZeroReflectValue(rv reflect.Value) bool {
    13  	switch rv.Kind() {
    14  	case reflect.Func, reflect.Map, reflect.Slice, reflect.Ptr:
    15  		return rv.IsNil()
    16  	case reflect.Array:
    17  		isAllZero := true
    18  		for i := 0; i < rv.Len(); i++ {
    19  			isAllZero = isAllZero && IsZeroReflectValue(rv.Index(i))
    20  		}
    21  
    22  		return isAllZero
    23  	case reflect.Struct:
    24  		isAllZero := true
    25  		for i := 0; i < rv.NumField(); i++ {
    26  			isAllZero = isAllZero && IsZeroReflectValue(rv.Field(i))
    27  		}
    28  
    29  		return isAllZero
    30  	}
    31  
    32  	// Compare other types directly:
    33  	z := reflect.Zero(rv.Type())
    34  
    35  	return rv.Interface() == z.Interface()
    36  }