gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/assert/assert.go (about) 1 package assert 2 3 import ( 4 "fmt" 5 "reflect" 6 ) 7 8 func Assert(b bool, msg string) { 9 if !b { 10 panic(msg) 11 } 12 } 13 14 func NotNil[V any](obj V, name string) V { 15 if any(obj) == nil || reflect.ValueOf(obj).IsNil() { 16 panic(fmt.Errorf("%s must be not nil", name)) 17 } 18 return obj 19 } 20 21 func PtrNotNil[V any](ptr *V, name string) *V { 22 if ptr == nil { 23 panic(fmt.Errorf("%s must be not nil", name)) 24 } 25 return ptr 26 } 27 28 func SliceNotNil[E any](slice []E, name string) []E { 29 if slice == nil { 30 panic(fmt.Errorf("%s must be not nil", name)) 31 } 32 return slice 33 } 34 35 func MapNotNil[K comparable, V any](m map[K]V, name string) map[K]V { 36 if m == nil { 37 panic(fmt.Errorf("%s must be not nil", name)) 38 } 39 return m 40 } 41 42 func ChanNotNil[E any](c chan E, name string) chan E { 43 if c == nil { 44 panic(fmt.Errorf("%s must be not nil", name)) 45 } 46 return c 47 } 48 49 func IsNil[V any](obj V, name string) V { 50 if any(obj) != nil && !reflect.ValueOf(obj).IsNil() { 51 panic(fmt.Errorf("%s must nil", name)) 52 } 53 return obj 54 } 55 56 func PtrIsNil[V any](ptr *V, name string) *V { 57 if ptr != nil { 58 panic(fmt.Errorf("%s must be not nil", name)) 59 } 60 return ptr 61 } 62 63 func NotEmpty[V any](obj V, name string) V { 64 Assert(reflect.ValueOf(obj).Len() != 0, fmt.Sprintf("%s must be not empty", name)) 65 return obj 66 } 67 68 func MustEmpty[V any](obj V, name string) V { 69 Assert(reflect.ValueOf(obj).Len() == 0, fmt.Sprintf("%s must be not empty", name)) 70 return obj 71 } 72 73 func NotZero[V any](obj V, name string) V { 74 Assert(!reflect.ValueOf(obj).IsZero(), fmt.Sprintf("%s must be not zero", name)) 75 return obj 76 } 77 78 func IsZero[V any](obj V, name string) V { 79 Assert(reflect.ValueOf(obj).IsZero(), fmt.Sprintf("%s must be not zero", name)) 80 return obj 81 }