github.com/zhongdalu/gf@v1.0.0/g/internal/empty/empty.go (about)

     1  // Copyright 2019 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  // Package empty provides checks for empty variables.
     8  package empty
     9  
    10  import (
    11  	"reflect"
    12  )
    13  
    14  // IsEmpty checks whether given <value> empty.
    15  // It returns true if <value> is in: 0, nil, false, "", len(slice/map/chan) == 0.
    16  // Or else it returns true.
    17  func IsEmpty(value interface{}) bool {
    18  	if value == nil {
    19  		return true
    20  	}
    21  	switch value := value.(type) {
    22  	case int:
    23  		return value == 0
    24  	case int8:
    25  		return value == 0
    26  	case int16:
    27  		return value == 0
    28  	case int32:
    29  		return value == 0
    30  	case int64:
    31  		return value == 0
    32  	case uint:
    33  		return value == 0
    34  	case uint8:
    35  		return value == 0
    36  	case uint16:
    37  		return value == 0
    38  	case uint32:
    39  		return value == 0
    40  	case uint64:
    41  		return value == 0
    42  	case float32:
    43  		return value == 0
    44  	case float64:
    45  		return value == 0
    46  	case bool:
    47  		return value == false
    48  	case string:
    49  		return value == ""
    50  	case []byte:
    51  		return len(value) == 0
    52  	default:
    53  		// Finally using reflect.
    54  		rv := reflect.ValueOf(value)
    55  		switch rv.Kind() {
    56  		case reflect.Chan,
    57  			reflect.Map,
    58  			reflect.Slice,
    59  			reflect.Array:
    60  			return rv.Len() == 0
    61  
    62  		case reflect.Func,
    63  			reflect.Ptr,
    64  			reflect.Interface,
    65  			reflect.UnsafePointer:
    66  			if rv.IsNil() {
    67  				return true
    68  			}
    69  		}
    70  	}
    71  	return false
    72  }