github.com/golang-infrastructure/go-reflect-utils@v0.0.0-20221130143747-965ef2eb09c3/nil.go (about)

     1  package reflect_utils
     2  
     3  import "reflect"
     4  
     5  // IsNil 判断参数是否为nil,当只有type但是value为nil的时候会认为是nil
     6  func IsNil(x any) bool {
     7  
     8  	if x == nil {
     9  		return true
    10  	}
    11  
    12  	v := reflect.ValueOf(x)
    13  	if !v.IsValid() {
    14  		return true
    15  	}
    16  
    17  	switch v.Kind() {
    18  	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Slice:
    19  		return v.IsNil()
    20  	case reflect.Ptr:
    21  		elem := v.Elem()
    22  		if elem.IsValid() {
    23  			return IsNil(elem.Interface())
    24  		} else {
    25  			return true
    26  		}
    27  	default:
    28  		return false
    29  	}
    30  }
    31  
    32  // IsNotNil 判断参数是否不为nil
    33  func IsNotNil(v any) bool {
    34  	return !IsNil(v)
    35  }