Skip to content

Commit

Permalink
Add IsNil function for checking nil values in Go (#399)
Browse files Browse the repository at this point in the history
  • Loading branch information
K4L1Ma committed Dec 2, 2023
1 parent 8f90a52 commit 2bbb3ea
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
6 changes: 6 additions & 0 deletions type_manipulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ func ToPtr[T any](x T) *T {
return &x
}

// IsNil checks if a value is nil or if it's a reference type with a nil underlying value.
func IsNil(x any) bool {
defer func() { recover() }()

Check failure on line 12 in type_manipulation.go

View workflow job for this annotation

GitHub Actions / lint

Error return value is not checked (errcheck)
return x == nil || reflect.ValueOf(x).IsNil()
}

// EmptyableToPtr returns a pointer copy of value if it's nonzero.
// Otherwise, returns nil pointer.
func EmptyableToPtr[T any](x T) *T {
Expand Down
24 changes: 24 additions & 0 deletions type_manipulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,30 @@ func TestToPtr(t *testing.T) {
is.Equal(*result1, []int{1, 2})
}

func TestIsNil(t *testing.T) {
t.Parallel()
is := assert.New(t)

var x int
is.False(IsNil(x))

var k struct{}
is.False(IsNil(k))

var s *string
is.True(IsNil(s))

var i *int
is.True(IsNil(i))

var b *bool
is.True(IsNil(b))

var ifaceWithNilValue interface{} = (*string)(nil)
is.True(IsNil(ifaceWithNilValue))
is.True(ifaceWithNilValue != nil)

Check failure on line 39 in type_manipulation_test.go

View workflow job for this annotation

GitHub Actions / lint

SA4023: this comparison is always true; the lhs of the comparison has been assigned a concretely typed value (staticcheck)
}

func TestEmptyableToPtr(t *testing.T) {
t.Parallel()
is := assert.New(t)
Expand Down

0 comments on commit 2bbb3ea

Please sign in to comment.