github.com/jxskiss/gopkg@v0.17.3/reflectx/reflect.go (about) 1 package reflectx 2 3 import ( 4 "github.com/jxskiss/gopkg/internal" 5 "reflect" 6 "unsafe" 7 ) 8 9 // IsNilInterface tells whether v is nil or the underlying data is nil. 10 func IsNilInterface(v interface{}) bool { 11 if v == nil { 12 return true 13 } 14 ef := EfaceOf(&v) 15 if ef.RType.Kind() == reflect.Slice { 16 return *(*unsafe.Pointer)(ef.Word) == nil 17 } 18 return ef.Word == nil 19 } 20 21 // IsIntType tells whether kind is an integer. 22 func IsIntType(kind reflect.Kind) bool { 23 switch kind { 24 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, 25 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 26 return true 27 } 28 return false 29 } 30 31 // ReflectInt returns v's underlying value as int64. 32 // It panics if v is not a integer value. 33 func ReflectInt(v reflect.Value) int64 { 34 switch v.Kind() { 35 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 36 return v.Int() 37 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 38 return int64(v.Uint()) 39 } 40 41 // shall not happen, type should be pre-checked 42 panic("bug: not int type") 43 } 44 45 // CastInt returns an integer v's value as int64. 46 // v must be an integer, else it panics. 47 func CastInt(v interface{}) int64 { 48 return internal.CastInt(v) 49 } 50 51 // CastIntPointer returns ptr's value as int64, the underlying value 52 // is cast to int64 using unsafe tricks according kind. 53 // 54 // If ptr is not pointed to an integer or kind does not match ptr, 55 // the behavior is undefined, it may panic or return incorrect value. 56 func CastIntPointer(kind reflect.Kind, ptr unsafe.Pointer) int64 { 57 return internal.CastIntPointer(kind, ptr) 58 }