Skip to content

Commit fde57e3

Browse files
committed
feat: add isNil helper function.
1 parent 5ba2235 commit fde57e3

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

util.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package assert
2+
3+
import "reflect"
4+
5+
// isNil checks whether a value is nil or not. It'll always return false if the value is not a
6+
// channel, a function, a map, a point, an unsafe point, an interface, or a slice.
7+
func isNil(val any) bool {
8+
if val == nil {
9+
return true
10+
}
11+
12+
v := reflect.ValueOf(val)
13+
14+
switch v.Kind() {
15+
case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.UnsafePointer,
16+
reflect.Interface, reflect.Slice:
17+
return v.IsNil()
18+
default:
19+
return false
20+
}
21+
}

util_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package assert
2+
3+
import "testing"
4+
5+
func TestIsNil(t *testing.T) {
6+
assert := New(t)
7+
8+
assert.DeepEqual(isNil(1), false) // int
9+
assert.DeepEqual(isNil(""), false) // string
10+
assert.DeepEqual(isNil(nil), true)
11+
var testAssert *Assertion
12+
assert.DeepEqual(isNil(testAssert), true)
13+
assert.DeepEqual(isNil(assert), false)
14+
}

0 commit comments

Comments
 (0)